function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ajay ambatiajay ambati 

batch apex error

iam new to the batch apex.here my question is batch apex job in exeute method iam passing list of accounts i,e 50,000 record ascynchronously and only 30,000 records inserted and remaining failed so,how to recognize the filed records where you found and how to reprocess that failed records?
JyothsnaJyothsna (Salesforce Developers) 
Hi Ajay,

Please check the below example.

Create a batch process on Accounts, capture the failures in a CSV file and send an email to the batch job creator.
 
global class BatchApexAccountUpdate implements Database.Batchable<SObject>, Database.Stateful{ 
    global Map<Id, String> errorMap {get; set;}
    global Map<Id, SObject> IdToSObjectMap {get; set;}

    global BatchApexAccountUpdate(){
        errorMap = new Map<Id, String>();
        IdToSObjectMap = new Map<Id, SObject>();
    }

    global Database.QueryLocator start(Database.BatchableContext BC) { 
        return Database.getQueryLocator('Select Id, OwnerId, Name From Account');
    } 

    global void execute(Database.BatchableContext BC, List<SObject> scope) { 
        List<Account> accountList = new List<Account>();
        for(SObject s : scope){
          Account acct = (Account) s;
          // Logic to update fields on the Account
           accountList.add(acct);
        }

        if(accountList.size() > 0) {
            List<Database.SaveResult> dsrs = Database.Update(accountList, false);
            Integer index = 0;
            for(Database.SaveResult dsr : dsrs){
                if(!dsr.isSuccess()){
                    String errMsg = dsr.getErrors()[0].getMessage();
                    errorMap.put(accountList[index].Id, errMsg);
                    IdToSObjectMap.put(accountList[index].Id, accountList[index]);
                }
                index++;
            }
        }
    } 

    global void finish(Database.BatchableContext BC) { 
       //Send an email to the User after your batch completes 
       if(!errorMap.isEmpty()){
            AsyncApexJob a = [SELECT id, ApexClassId,
                       JobItemsProcessed, TotalJobItems,
                       NumberOfErrors, CreatedBy.Email
                       FROM AsyncApexJob
                       WHERE id = :BC.getJobId()];
            String body = 'Your batch job '
             + 'BatchApexAccountUpdate '
             + 'has finished. \n' 
             + 'There were '
             + errorMap.size()
             + ' errors. Please find the error list attached to the Case.';

            // Creating the CSV file
            String finalstr = 'Id, Name, Error \n';
            String subject = 'Account - Apex Batch Error List';
            String attName = 'Account Errors.csv';
            for(Id id  : errorMap.keySet()){
                string err = errorMap.get(id);
                Account acct = (Account) IdToSObjectMap.get(id);
                string recordString = '"'+id+'","'+acct.Name+'","'+err+'"\n';
                finalstr = finalstr +recordString;
            } 

            // Define the email
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 

            // Create the email attachment    
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setFileName(attName);
            efa.setBody(Blob.valueOf(finalstr));

            // Sets the paramaters of the email
            email.setSubject( subject );
            email.setToAddresses( new String[] {a.CreatedBy.Email} );
            email.setPlainTextBody( body );
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
            }
    } 
}



To run the batch job in the anonymous window.
 
BatchApexAccountUpdate updateAcct = new BatchApexAccountUpdate();
Id batchApexCommId = Database.executeBatch(updateAcct);

Hope this helps you!
Best Regards,
Jyothsna
ajay ambatiajay ambati
that means iam asking that how would i know that which records are not inserted 
ajay ambatiajay ambati
is possible with debug logs