• #29609
     Prachi #6

    How to handle error records in Salesforce Batch apex?

    How to handle error records in Salesforce Batch apex?



    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=”;
    msg += userList.get(i).id + ‘\n’+’Error: “‘;
    for(Database.Error err: SaveResultList[i].getErrors()){
    msg += err.getmessage()+'”\n\n’;
    You can use this exception_list in execute method to send in your final email.


    Salesforce | Parul Parul #2

    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) {
    public void finish(…) {
    if(!errors.isEmpty()) {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject(‘Errors occurred during batch process.’);
    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.

Viewing 3 posts - 1 through 3 (of 3 total)

Please to reply to this topic.


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2019 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?