Introduction

This article intents to show how we can save state of batch class member variables for all serial batch jobs running in background for a single batch job.

Use Cases

  • When you want to report the batch execution status.
  • Calculate records failed/passed on some criteria.
  • See most common error occurred while batch run etc.

Example

Lets take a simple example for sending email with all errors occurred when a batch job is finished execution.

public class MyBatchUpload implements Database.Stateful, Database.Batchable < sObject > {

    public List < String > errors {
        get;
        set;
    }

    public List < MyCustomObject__c > start(Database.BatchableContext BC) {
        return [SELECT Id, Name FROM MyCustomObject__c];
    }

    public void execute(Database.BatchableContext BC, List < MyCustomObject__c > scope) {
        Savepoint sp = Database.setSavepoint();
        Database.DMLOptions dml = new Database.DMLOptions();
        dml.DuplicateRuleHeader.allowSave = false;
        Database.SaveResult[] srList = Database.insert(scope, dml);
        for (Database.SaveResult sr: srList) {
            if (!sr.isSuccess()) {
                for (Database.Error err: sr.getErrors()) {
                    errors.add(err.getStatusCode() + ', MESSAGE=[' + err.getMessage() + '], FIELDS=[' + err.getFields() + ']');
                }
            }
        }
    }

    public void finish(Database.BatchableContext BC) {
        //*** Here you can use the errors list and send an email or save as file **
        //*** for every run it keeps on maintaining the state of errors list so that you can use it in finish method for some metrics or progress purpose **
    }

}