EventBus.EventPublishSuccessCallback and EventBus.EventPublishFailureCallback interfaces can be used in an Apex Class to track Successful and Failure Salesforce Platform Events.
Sample Apex Class:
public class PlatformEventHandler implements
EventBus.EventPublishSuccessCallback,
EventBus.EventPublishFailureCallback
{
public void onSuccess(
EventBus.SuccessResult successResult
) {
List < String > eventUUIDs
= successResult.getEventUuids();
List < Platform_Event_Log__c > listPELs
= new List < Platform_Event_Log__c >();
for (
String strUUID : eventUUIDs
) {
listPELs.add(
new Platform_Event_Log__c(
Type__c = 'Success',
UUID__c = strUUID
)
);
}
if ( listPELs.size() > 0 ) {
insert listPELs;
}
}
public void onFailure(
EventBus.FailureResult failureResult
) {
List < String > eventUUIDs
= failureResult.getEventUuids();
List < Platform_Event_Log__c > listPELs
= new List < Platform_Event_Log__c >();
for ( String strUUID : eventUUIDs ) {
listPELs.add(
new Platform_Event_Log__c(
Type__c = 'Failure',
UUID__c = strUUID
)
);
}
if ( listPELs.size() > 0 ) {
insert listPELs;
}
}
}
In my example, I am creating records for all the Platform Events Success and Failure events in a Custom Object for tracking purpose.
When we publish the Platform Events using EventBus.publish() method, we have to pass the callback class object.
Sample Apex Code to publish Platform Events with Callback class:
PlatformEventHandler objPEH = new PlatformEventHandler();
List < Employee__e > listEvents = new List <Employee__e >();
listEvents.add(
new Employee__e(
Employee_Number__c = '12345',
Message__c = 'Testing'
)
);
List < Database.SaveResult > results
= EventBus.publish( listEvents, objPEH );
for ( Database.SaveResult sr : results ) {
if ( sr.isSuccess() ) {
System.debug(
'Event successfully published event.'
);
} else {
for (
Database.Error err : sr.getErrors()
) {
System.debug(
'Error code: ' +
err.getStatusCode()
);
System.debug(
'Error message: ' +
err.getMessage()
);
}
}
}