Skip to content

Instantly share code, notes, and snippets.

@bobbyjam99-zz
Last active November 8, 2020 18:47
Show Gist options
  • Save bobbyjam99-zz/74c5d2fd120153bacce4b23040a77220 to your computer and use it in GitHub Desktop.
Save bobbyjam99-zz/74c5d2fd120153bacce4b23040a77220 to your computer and use it in GitHub Desktop.
trigger BatchApexErrorTrigger on BatchApexErrorEvent (after insert) {
List<BatchLeadConvertErrors__c> errors = new List<BatchLeadConvertErrors__c>();
for(BatchApexErrorEvent event : Trigger.New) {
BatchLeadConvertErrors__c blcerror = new BatchLeadConvertErrors__c();
blcerror.AsyncApexJobId__c = event.AsyncApexJobId;
blcerror.Records__c = event.JobScope;
blcerror.StackTrace__c = event.StackTrace;
errors.add(blcerror);
}
if (errors.size() > 0) {
insert errors;
}
}
public with sharing class BatchLeadConvert implements Database.Batchable<SObject>, Database.RaisesPlatformEvents {
private final String CONVERTED_STATUS = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1].MasterLabel;
public Database.QueryLocator start(Database.BatchableContext ctx){
return Database.getQueryLocator([SELECT Id FROM Lead WHERE ConvertedContactId = null]);
}
public void execute(Database.BatchableContext ctx, List<Lead> records){
List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
for(Lead record:records){
Database.LeadConvert lc = new Database.LeadConvert();
lc.setConvertedStatus(CONVERTED_STATUS);
lc.setLeadId(record.Id);
leadConverts.add(lc);
}
Database.convertLead(leadConverts, true);
}
public void finish(Database.BatchableContext ctx){
}
}

Modify an existing batch Apex job to raise BatchApexErrorEvents

Take an existing batch Apex job class and update it to implement the Database.RaisesPlatformEvents interface. Then, add a trigger on BatchApexErrorEvent that logs exceptions in the batch job to a custom object.

  • Update the BatchLeadConvert class to implement the Database.RaisesPlatformEvents marker interface.
  • Create an Apex trigger called BatchApexErrorTrigger on the BatchApexErrorEvent SObject type. For each event record, capture the following fields and save them to the corresponding fields in a new BatchLeadConvertErrors__c record.
    • AsyncApexJobId: AsyncApexJobId__c
    • JobScope: Records__c
    • StackTrace: StackTrace__c
  • To make the trigger bulk safe, use a single DML statement to insert a list of new records at the end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment