Building Resilient Integration in case error occurs during execution of batch Apex Class

When you are integrating with external system using Batch Apex, you can implement Database.RaisesPlatformEvents interface to generate BatchApexErrorEvent event which external system can subscribe to listen in case of error.

Streaming API Subscription Channel:

/event/BatchApexErrorEvent

Example:

public with sharing class TestBatch implements Database.Batchable<sObject>, Database.RaisesPlatformEvents {
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'SELECT Id FROM Account';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext BC, List<SObject> scope){
        Integer i = 1 / 0;
    }

    public void finish(Database.BatchableContext BC){ }
}

Listening to the event using trigger:

trigger LogBatchApexErrorEvent on BatchApexErrorEvent (after insert){
    if(Trigger.IsInsert && Trigger.IsAfter){
        LogBatchApexErrorEvent_Handler.persistLog(Trigger.New);
    }
}

Test Class:

static testMethod void testBatchApexErrorEvent() {
   insert new Account(Name = 'Test Account');

   try{
        Test.startTest();
        TestBatch tb = new TestBatch();
        Database.executeBatch(tb); 
        Test.stopTest();
    } catch(System.MathException e){}
    Test.getEventBus().deliver(); 

    System.assertEquals(1, [SELECT Id FROM Log__c].size());
}

Note: Please don’t forget to use ‘Test.getEventBus().deliver();’ to fire platform event in test class

For information like what information will be passed in the event, please check this link

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

Leave a Reply