How do you handle partial success and error isolation when performing DML updates in Batch Apex?
Answer
Basics: A plain update fails the entire chunk if one record fails. With allOrNone=false, valid records are saved and each failure is reported per record, so one bad row does not block 199 good ones.
How it works:
- Call
Database.update(scope, false)and captureList<Database.SaveResult>. - Loop with an index; for each failed result, read
getErrors()andscope[i].Id. - Store failures (Stateful list, a log object, or a platform event).
- Report in
finish().
Advanced / deep dive: Partial success covers DML-level errors such as validation, required fields and trigger addError; it does not stop uncatchable limit exceptions, which roll back the whole chunk. For unhandled exceptions, implement Database.RaisesPlatformEvents on the batch class so Salesforce publishes BatchApexErrorEvent records that a trigger can consume to log failures. Using Database.Stateful to accumulate errors costs heap, so persist logs to a custom object (insert once per chunk) instead of growing a list forever. Upsert returns UpsertResult, delete returns DeleteResult. Remember that partial success means a record rolled back from a validation rule still counted its DML row.
Code / config example:
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) { a.Rating = ; }
List<Database.SaveResult> results = Database.update(scope, );
List<Error_Log__c> logs = <Error_Log__c>();
( ; i < results.size(); i++) {
(!results[i].isSuccess()) {
logs.add( (
Record_Id__c = scope[i].Id,
Message__c = results[i].getErrors()[].getMessage()
));
}
}
(!logs.isEmpty()) insert logs;
}