Understanding the Error Handling in Batch Apex
Batch Apex processes large volumes of records asynchronously in Salesforce. When errors occur during execution, only the current scope is rolled back, not the entire job. This creates a need for robust error handling strategies to track failures and ensure data integrity.
Causes of Error Records in Batch Apex
-
Validation rule violations or trigger failures that prevent records from being saved.
-
Governor limit exceptions such as hitting SOQL or DML limits during batch processing.
-
Data inconsistencies where records don't meet the conditions required for processing.
-
External API failures when batch jobs make callouts to external systems.
How to Handle Error Records in Batch Apex
1. Implement Database.Stateful
Add the Database.Stateful interface to your batch class to maintain state between transactions:
apexpublic class MyBatch implements Database.Batchable<SObject>, Database.Stateful { private List<String> errorMessages = new List<String>(); private Integer successCount = 0; private Integer failureCount = 0; // Implement batch methods... }
2. Use Partial Processing with Database Methods
Instead of standard DML operations, use Database methods with the allOrNone parameter set to false:
apexDatabase.SaveResult[] results = Database.update(recordsToUpdate, false); for(Integer i = 0; i < results.size(); i++) { if(!results[i].isSuccess()) { // Collect error information for(Database.Error err : results[i].getErrors()) { errorMessages.add('Record ID: ' + recordsToUpdate[i].Id + ' Error: ' + err.getMessage()); } } }
3. Send Email Notifications
Create email notifications in the finish method to report on errors:
apexpublic void finish(Database.BatchableContext BC) { if(!errorMessages.isEmpty()) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setSubject('Batch Process Results'); mail.setTargetObjectId(UserInfo.getUserId()); mail.setSaveAsActivity(false); mail.setPlainTextBody('Errors encountered: ' + errorMessages); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
4. Implement BatchApexErrorEvent
For advanced error handling, leverage the BatchApexErrorEvent:
apex// In your trigger handler trigger BatchApexErrorEventTrigger on BatchApexErrorEvent (after insert) { BatchErrorHandler.processErrors(Trigger.new); }
This platform event provides detailed error information including record IDs, exception type, and stack trace.
Conclusion
Effective error handling in Batch Apex is essential for building resilient Salesforce applications. By implementing these strategies, you can ensure that batch processes continue even when individual records fail, while maintaining visibility into errors for troubleshooting.
Remember to always test your error handling logic thoroughly with different failure scenarios. This proactive approach will help you build more robust batch processes that can gracefully recover from unexpected errors.