Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Created August 30, 2019 15:11
Show Gist options
  • Save mhamzas/bb680484b27f65df70e85ac8e3864a6a to your computer and use it in GitHub Desktop.
Save mhamzas/bb680484b27f65df70e85ac8e3864a6a to your computer and use it in GitHub Desktop.
Modify an existing batch Apex job to raise BatchApexErrorEvents
trigger BatchApexErrorTrigger on BatchApexErrorEvent (after insert) {
List<BatchLeadConvertErrors__c> List_LeadConvertError = new List<BatchLeadConvertErrors__c>();
for(BatchApexErrorEvent event: trigger.new){
BatchLeadConvertErrors__c lcerror = new BatchLeadConvertErrors__c();
lcerror.AsyncApexJobId__c = event.AsyncApexJobId;
lcerror.Records__c = event.JobScope;
lcerror.StackTrace__c = event.StackTrace;
List_LeadConvertError.add(lcerror);
}
if(List_LeadConvertError.size() > 0 && List_LeadConvertError != null){
insert List_LeadConvertError;
}
}
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){
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment