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 {}
}