How to handle error records in Batch apex?

  1. first of all you need to make your batch class stateful using Database.Stateful so replace your first line with

    public class SimpleBatch implements Database.Batchable<sObject>,Database.Stateful{
    
  2. A global variable required which will maintain failed record.

    global List<String> exception_List;
    
  3. Use Database.update method instead of update with allOrNothing = false parameter which will return how many records has passed and failed in update call.

    Database.SaveResult[] SaveResultList = Database.update(objsToUpdate,false);   
    
  4. You will iterate saveResultList and you will add failed records in exception_list

     for(integer i =0; i<objsToUpdate.size();i++){
            String msg='';
            If(!SaveResultList[i].isSuccess()){
                    msg += userList.get(i).id + '\n'+'Error: "';        
                    for(Database.Error err: SaveResultList[i].getErrors()){  
                         msg += err.getmessage()+'"\n\n';
                    } 
            }
            if(msg!='')
                exception_List.add(msg);
         } 
    
  5. You can use this exception_list in execute method to send in your final email.


Some things to do:

  1. Have your batch class implement Database.stateful
  2. Declare some variables that are initialized in the constructor to 0. These variables count successes and errors; also a string variable that remembers the records that failed and why (initialized to empty string).
  3. Use Database.update with allOrNothing = false instead of update within execute(). Interrogate each member of Database.SaveResult[] for isSuccess() and count succcesses and failures in your stateful variables from #2. Log in the stateful variable all the errors (id of record, name of record, and error message/exception)
  4. In the finish method, send an email to the sysad of count of successes/failures + string variable of all the failures.
  5. In finish() method, write your batch results to a custom Log__c record(s)

Tags:

Apex

Batch