Fire Platform Events from Batch Apex Classes
Automatic Event Generator Batch Class
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){
trigger BatchApexErrorTrigger on BatchApexErrorEvent (after insert) {
List<BatchLeadConvertErrors__c> errorLogList = new List<BatchLeadConvertErrors__c>();
for(BatchApexErrorEvent evt : Trigger.new){
BatchLeadConvertErrors__c errorLog = new BatchLeadConvertErrors__c();
errorLog.AsyncApexJobId__c = evt.AsyncApexJobId;
errorLog.Records__c = evt.JobScope;
errorLog.StackTrace__c = evt.StackTrace;
errorLogList.add(errorLog);
}
insert errorLogList;
}
Note : Here BatchLeadConvertErrors__c is a custom object we used to track the error logs.