Activity › Forums › Salesforce® Discussions › How to handle error records in Batch apex in Salesforce?
Tagged: Batch Apex, Constructor, Custom Log, Database SaveResult, Database Stateful, Database Update, Error Records, Finish Method, String Variables
-
How to handle error records in Batch apex in Salesforce?
Posted by madhulika shah on August 21, 2018 at 1:05 PMHow to handle error records in Batch apex in Salesforce?
Parul replied 7 years, 7 months ago 4 Members · 3 Replies -
3 Replies
-
Hi Madhulika,
Things you can do:
- Have your batch class implement Database.stateful
- Declare some variables that are initialized in the constructor to 0. These variables count successes and errors; also a string variable that remembers the records that failed and why (initialized to empty string).
- Use Database.update with allOrNothing = false instead of update within execute(). Interrogate each member of Database.SaveResult[] for isSuccess() and count succcesses and failures in your stateful variables from #2. Log in the stateful variable all the errors (id of record, name of record, and error message/exception)
- In the finish method, send an email to the sysad of count of successes/failures + string variable of all the failures.
- In finish() method, write your batch results to a custom Log__c record(s)
- [adinserter block='9']
-
Hi,
You can handle errors in batch related records as shown below –
if (accountstoUpd.size() > 0) {
Database.SaveResult[] lsr = Database.update(accountstoUpd,false);
Integer recordid = 0;
for (Database.SaveResult SR : lsr) {
if (!SR.isSuccess()) {
this.errormsgs += ‘Account Record:’ + accountstoUpd[recordid].id + ‘, ‘ + SR.getErrors()[0].getMessage() + ‘<br/>’;
}
recordid++;
}
}
if (this.errormsgs.length() > 0) {
ErrorLogs__c errtoSave = new ErrorLogs__c(details__c = this.errormsgs);
insert errtoSave;
}Hope this helps.
-
Hi
Some things to do:
Have your batch class implement Database.stateful
Declare some variables that are initialized in the constructor to 0. These variables count successes and errors; also a string variable that remembers the records that failed and why (initialized to empty string).
Use Database.update with allOrNothing = false instead of update within execute(). Interrogate each member of Database.SaveResult[] for isSuccess() and count succcesses and failures in your stateful variables from #2. Log in the stateful variable all the errors (id of record, name of record, and error message/exception)
In the finish method, send an email to the sysad of count of successes/failures + string variable of all the failures.
In finish() method, write your batch results to a custom Log__c record(s)Thanks
Log In to reply.