Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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;
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();
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