Newer Version Available

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

Publish Event Messages with Apex

Use Apex to publish event messages from a Salesforce app.

To publish event messages, call the EventBus.publish method. For example, if you’ve defined a custom platform event called Low Ink, reference this event type as Low_Ink__e. Next create instances of this event and pass them to the Apex method.

Example

This example creates two events of type Low_Ink__e, publishes them, and then checks whether the publishing was successful or errors were encountered. The example assumes that the Low Ink platform event is defined in your org.

1List<Low_Ink__e> inkEvents = new List<Low_Ink__e>();
2inkEvents.add(new Low_Ink__e(Printer_Model__c='XZO-5', Serial_Number__c='12345', 
3              Ink_Percentage__c=0.2));
4inkEvents.add(new Low_Ink__e(Printer_Model__c='MN-123', Serial_Number__c='10013', 
5              Ink_Percentage__c=0.15));
6
7
8// Call method to publish events
9List<Database.SaveResult> results = EventBus.publish(inkEvents);
10
11// Inspect publishing result for each event
12for (Database.SaveResult sr : results) {
13    if (sr.isSuccess()) {
14        System.debug('Successfully published event.');
15    } else {
16        for(Database.Error err : sr.getErrors()) {
17            System.debug('Error returned: ' +
18                        err.getStatusCode() +
19                        ' - ' +
20                        err.getMessage());
21        }
22    }       
23}
For each event, Database.SaveResult contains information about whether the operation was successful and the errors encountered. If the isSuccess() method returns true, the event was published. Otherwise, the event publish operation resulted in errors which are returned in the Database.Error object. EventBus.publish() can publish some passed-in events, even when other events can’t be published due to errors. The EventBus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation. It is similar in behavior to the Apex Database.insert method when called with the partial success option.

The event insertion occurs non-transactionally. As a result, you can’t roll back published events. Because event publishing is equivalent to a DML insert operation, DML limits and other Apex governor limits apply.