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.