Activity Forums Salesforce® Discussions How to handle error records in Salesforce Batch apex?

  • shradha jain

    Member
    August 3, 2018 at 4:57 am

    Hello Prachi,

    First of all you need to make your batch class stateful using Database.Stateful .

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

    global List<String> exception_List;
    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);
    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);
    }
    You can use this exception_list in execute method to send in your final email.

    Thanks.

  • Parul

    Member
    September 28, 2018 at 5:23 pm

    Yes, you can certainly send an email to the user; in fact, this is my preferred method to avoid spamming users. You can do this by way of the Database.Stateful.

    public class MyBatchable implements Database.Batchable<SObject>, Database.Stateful {
    Exception[] errors = new Exception[0];
    public Iterable<SObject> start(...) {
    ...
    }
    public void execute(...) {
    try {
    ...
    } catch(Exception e) {
    errors.add(e);
    }
    }
    public void finish(...) {
    if(!errors.isEmpty()) {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('Errors occurred during batch process.');
    mail.setTargetObjectId(UserInfo.getUserId());
    mail.setSaveAsActivity(false);
    mail.setPlainTextBody(buildBodyFor(errors));
    Messaging.sendEmail(new Messaging.Email[] { mail });
    }
    }
    }
    You might also include a way to send emails if too many errors have stacked up, or limit yourself to some number of exceptions (say, the first 50 or 100). Keep in mind that you do have a limited amount of memory available, so if you're concerned about having a large number of errors, consider logging them to the database and then querying them back in your finish method.

  • badari

    Member
    July 12, 2022 at 3:27 pm

    Above solutions should work. Probably a better/new way would be using Events driven approach via Platform Events. Please refer below link
    https://developer.salesforce.com/docs/atlas.en-us.236.0.platform_events.meta/platform_events/sforce_api_objects_batchapexerrorevent.htm

  • CRMJetty

    Member
    August 9, 2022 at 4:18 am

Log In to reply.

Popular Salesforce Blogs