Newer Version Available

This content describes an older version of this product. View Latest

Example: Publish Events with a Callback Instance

To invoke the callback, perform an EventBus.publish call by passing it an instance of the FailureCallback class. You can publish one event or a batch of events with the callback.

This example publishes two event messages. This example requires a platform event, Order Event, to be defined with a Text(18) field of Order Id. To view debug logs for the FailureCallback class, make sure that you set up user trace flags for the Automated Process user. For more information, see Callback Running User and Debug Logs. In this case, if all publishing is successful, the onFailure() method isn’t invoked.

1List<Order_Event__e> eventList = new List<Order_Event__e>();
2
3// Create event objects with prepopulated EventUuid fields.
4Order_Event__e event1 = (Order_Event__e)Order_Event__e.sObjectType.newSObject(null, true);
5event1.Order_Id__c='Order1 ID';
6System.debug('event1 EventUuid: ' + event1.EventUuid);
7
8
9Order_Event__e event2 = (Order_Event__e)Order_Event__e.sObjectType.newSObject(null, true);
10event2.Order_Id__c='Order2 ID';
11System.debug('event2 EventUuid: ' + event2.EventUuid);
12
13// Add event objects to the list.
14eventList.add(event1);
15eventList.add(event2);
16
17// Publish events with an instance of the failure callback.
18List<Database.SaveResult> results = EventBus.publish(eventList, new FailureCallback());
19
20// Inspect synchronous publishing result for each event.
21for (Database.SaveResult sr : results) {
22    if (sr.isSuccess()) {
23        System.debug('Successfully published event.');
24    } else {
25        for(Database.Error err : sr.getErrors()) {
26            System.debug('Error returned: ' +
27                        err.getStatusCode() +
28                        ' - ' +
29                        err.getMessage());
30        }
31    }
32}