Newer Version Available

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

Subscribe to Publish Status Events with an Apex Trigger

Alternatively, you can subscribe to publish status events with an Apex trigger. Create an after insert trigger on PublishStatusEvent.

Trigger.New contains the received PublishStatusEvent messages. For each status event, you can obtain the event fields, such as the status and topic. Then you can get information about each event, including the EventUuid, in the PublishStatusDetails field.

This Apex trigger example iterates over every PublishStatusEvent and logs information about the failed event publishes in PublishResult__c custom object records.

Prerequisites: Before you can save this example, create a custom object with the label PublishResult and with these fields:

  • Type: Text(36), Label: EventUuid
  • Type: Number(18,0), Label: ReplayId
  • Type: Text(50), Label: StatusCode
  • Type: Text(255), Label: FailureReason
  • Type: Text(255), Label: Topic
  • Type: Text(25), Label: Status
1trigger StatusEventTrigger on PublishStatusEvent (after insert) {
2    for (PublishStatusEvent event : Trigger.New) {
3        System.debug('Event Name:' + event.Topic);
4        System.debug('Event status:' + event.Status);
5        
6        // Get the publish details for all events included
7        List<PublishStatusDetail> details = event.PublishStatusDetails;
8        // List of custom object records to insert later
9        List<PublishResult__c> resultsToInsert = new List<PublishResult__c>();
10        
11        // Log failed publishes in custom object records
12        if (event.Status == 'FAILURE') { 
13            for(PublishStatusDetail detail : details) {
14                // Populate custom object record
15                PublishResult__c result = new PublishResult__c();
16                result.EventUuid__c = detail.EventUuid;
17                result.ReplayId__c = detail.Replay;
18                result.StatusCode__c = detail.StatusCode;
19                result.FailureReason__c = detail.FailureReason;
20                // Get fields from parent event object
21                result.Topic__c = event.Topic;
22                result.Status__c = event.Status;
23                // Add to list of records to insert
24                resultsToInsert.add(result);
25            }
26            // Insert custom object records in bulk
27            Database.insert(resultsToInsert); 
28        }
29    }
30}