Newer Version Available

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

Refire Event Triggers with EventBus.RetryableException

Refiring an event trigger gives you another chance to process event notifications. Refiring a trigger is helpful when a transient error occurs or when waiting for a condition to change. Refire a trigger if the error or condition is external to the event records and is likely to go away later.

For example, a trigger adds a related record to a master record if a field on the master record equals a certain value. It is possible that in a subsequent try, the field value changes and the trigger can perform the operation.

To refire the event trigger, throw EventBus.RetryableException. The event is resent after a small delay. The delay increases with each subsequent retry. A resent event has the same field values as the original event, but the batch sizes of the events can differ. For example, the initial trigger can receive events with replay ID 10 to 20. The resent batch can be larger, containing events with replay ID 10 to 40.

This example is a skeletal trigger that gives you an idea of how to throw EventBus.RetryableException. The trigger uses an if statement to check whether a certain condition is true. Alternatively, you can use a try-catch block and throw EventBus.RetryableException in the catch block.

1trigger ResendEventsTrigger on Low_Ink__e (after insert) {
2    if (condition == true) {        
3        // Process platform events.        
4    } else {
5        // Condition isn't met, so try again later.
6        throw new EventBus.RetryableException();
7    }
8}

The previous example refires the trigger every time the condition isn’t met by throwing EventBus.RetryableException. But what if you want to place a limit on how many times you want to refire the trigger? For example, refire the trigger for up to three times only. This is when the EventBus.TriggerContext class comes in handy. The EventBus.TriggerContext.currentContext() returns an instance of the EventBus.TriggerContext class that contains information about the currently executing trigger. Calling the retries property on this instance gets the number of times the trigger was refired.

1trigger ResendEventsTrigger on Low_Ink__e (after insert) {
2    if (condition == true) {        
3        // Process platform events.        
4    } else {
5    // Ensure we don't refire the trigger more than 3 times
6    if (EventBus.TriggerContext.currentContext().retries < 4) {
7        // Condition isn't met, so try again later.
8        throw new EventBus.RetryableException(
9                     'Condition is not met, so retrying the trigger again.');
10    } else {
11        // Trigger was refired enough times so give up and
12        // resort to alternative action.
13        // For example, send email to user.
14    }
15}