Sub topic 9
Handling partial failures
This chapter assumes you can write a basic batch class with start, execute and finish, and that you know DML (data manipulation language) statements and the Database.Stateful interface.
Why one bad record matters
Each execute call runs in its own transaction. If a plain update scope; hits one record that fails validation, the whole DML statement throws an exception. The transaction rolls back and none of the records in that chunk are saved. Earlier chunks stay committed, and later chunks still run. The result is a job where some chunks of 200 records are saved and others are silently lost.
Use the partial-save form of DML to avoid this. Database.update(records, false) sets allOrNone to false. Valid records are saved. Invalid records are skipped and reported in the returned results.
Inspecting the results
Database.update returns a List<Database.SaveResult> in the same order as the input list. Each result tells you whether that record saved and, if not, why.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer succeeded = 0;
public Integer failed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Database.SaveResult sr : results) {
if (sr.isSuccess()) {
succeeded++;
} else {
failed++;
for (Database.Error err : sr.getErrors()) {
System.debug('Update failed: ' + err.getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
System.debug('Status: ' + job.Status + ', succeeded: ' + succeeded + ', failed: ' + failed);
}
}Three points about this code:
Database.Statefulkeepssucceededandfailedalive betweenexecutecalls. Without it, both fields reset to 0 for every chunk.sr.isSuccess()separates good records from bad ones.sr.getErrors()returns a list ofDatabase.Errorobjects, each with a message and the fields involved.finishqueriesAsyncApexJobto read the job's final status next to your own counters.
What partial save does not cover
Partial save only handles errors that DML reports per record, such as validation rules, required fields and trigger addError calls. Other failures still abort the chunk:
- An uncaught exception in your code, such as a null pointer or a
QueryException. - A governor limit error, such as too many DML rows or too much CPU time.
When that happens, Salesforce rolls back that execute call, counts it toward NumberOfErrors on the AsyncApexJob, and moves on to the next chunk. Your finish method still runs.
Keeping the failures
Debug logs are short-lived and hard to search at scale. For a job that processes millions of records, store the failed record Ids and messages in a stateful list. Then write them to a custom object or send a summary email from finish. Keep the list small, because stateful data is serialized between chunks and counts toward heap size.
Exercise
A batch execute method calls update scope; and one record in a chunk of 200 fails a validation rule. What happens to the other 199 records, and what change lets them save?
Show answer
The DML statement throws an exception, so the whole chunk is rolled back and none of the 199 records are saved. Replace it with Database.update(scope, false) and check each Database.SaveResult. Valid records then save and only the failing record is reported.
Exercise
Why does the failed counter in the example stay at 0 in finish if the class does not implement Database.Stateful?
Show answer
Without Database.Stateful, a new instance of the class is created for each execute call and field values are not kept between calls. The counters reset every chunk, so finish sees the initial values.