1

I was working on something entirely different, wrote a test code and found a gap in my knowledge. Hoping someone can point out where and why my understanding is wrong.

I have a batch job, it queries 10 cases. There is a loop that iterates over cases retrieved. In a loop, in the third iteration, i am throwing a custom error. But other iterations, i am inserting a record of testObject__c.

I thought, that i would see 2 records of testObject__c, but there are no records created. Does the batch job rolls back the DML operations of a chunk if an error is encountered? What if there are multiple chunks .. does it roll back all of it, or just the chunk where an error happened?

global with sharing class testBatch implements Database.Batchable<sObject>{

    public testBatch(){}

    global Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'Select Id From Case limit 10';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Case> allCases){
        Integer i=1;
        for(Case c : allCases){
            System.debug(i);
            
            if(i==3){
                throw new MissingRequiredFieldsException('Something went wrong '); 
            }else{
                testObject__c tobj = new testObject__c();
                tobj.Name = 'testObject'+String.valueOf(i);
                insert tobj;
            }
        
            
            i++;
        }
    }

    global void finish(Database.BatchableContext BC){

    }

    class MissingRequiredFieldsException extends Exception {}
}
0

Does the batch job rolls back the DML operations of a chunk if an error is encountered?

Yes.

If an unhandled exception occurs, all work done in the execute method will be rolled back. This is the same behavior you'd see in a trigger, future method, queueable, etc. Never allow an exception to be thrown to the top unless you want to abort the transaction entirely.

What if there are multiple chunks .. does it roll back all of it, or just the chunk where an error happened?

Just the failures are rolled back.

If there are multiple calls to the execute method (e.g. more than one batch worth of records), each are treated independently. This means that if you have, for example, 3 batches, and the second batch failed, both the first and third batch could still succeed, independent of the second execute method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.