Skip to content

Instantly share code, notes, and snippets.

@dirajkumar
Last active August 9, 2023 14:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dirajkumar/8710340 to your computer and use it in GitHub Desktop.
Save dirajkumar/8710340 to your computer and use it in GitHub Desktop.
Apex Snippet: Handling Erroneous Records using Batch Apex
global class BatchApexAccountUpdate implements Database.Batchable<SObject>, Database.Stateful{
global Map<Id, String> errorMap {get; set;}
global Map<Id, SObject> IdToSObjectMap {get; set;}
global BatchApexAccountUpdate(){
errorMap = new Map<Id, String>();
IdToSObjectMap = new Map<Id, SObject>();
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator('Select Id, OwnerId, Name From Account');
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
List<Account> accountList = new List<Account>();
for(SObject s : scope){
Account acct = (Account) s;
// Logic to update fields on the Account
accountList.add(acct);
}
if(accountList.size() > 0) {
List<Database.SaveResult> dsrs = Database.Update(accountList, false);
Integer index = 0;
for(Database.SaveResult dsr : dsrs){
if(!dsr.isSuccess()){
String errMsg = dsr.getErrors()[0].getMessage();
errorMap.put(accountList[index].Id, errMsg);
IdToSObjectMap.put(accountList[index].Id, accountList[index]);
}
index++;
}
}
}
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
if(!errorMap.isEmpty()){
AsyncApexJob a = [SELECT id, ApexClassId,
JobItemsProcessed, TotalJobItems,
NumberOfErrors, CreatedBy.Email
FROM AsyncApexJob
WHERE id = :BC.getJobId()];
String body = 'Your batch job '
+ 'BatchApexAccountUpdate '
+ 'has finished. \n'
+ 'There were '
+ errorMap.size()
+ ' errors. Please find the error list attached to the Case.';
// Creating the CSV file
String finalstr = 'Id, Name, Error \n';
String subject = 'Account - Apex Batch Error List';
String attName = 'Account Errors.csv';
for(Id id : errorMap.keySet()){
string err = errorMap.get(id);
Account acct = (Account) IdToSObjectMap.get(id);
string recordString = '"'+id+'","'+acct.Name+'","'+err+'"\n';
finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Sets the paramaters of the email
email.setSubject( subject );
email.setToAddresses( new String[] {a.CreatedBy.Email} );
email.setPlainTextBody( body );
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment