1

If my Platform Event is configured to have a custom field Key_Field__c.

How do I get the value of Key_Field__c on the Platform Event object which has failed when using EventBus.publish()

void createEvents() {

    List<My_Custom_Event__e > events = new List<My_Custom_Event__e>();
    events.add(new My_Custom_Event__e(Key_Field__c = 'key field value 1'));
    events.add(new My_Custom_Event__e(Key_Field__c = 'key field value 2'));
    handleSaveResults(EventBus.publish(events));
}

void handleSaveResults(Database.SaveResult[] results) {

    for (Database.SaveResult result : results) {
        if (result.isSuccess() == false) {
            for (Database.Error err : result.getErrors()) {
                String statusCode = err.getStatusCode();
                String message = err.getMessage();
                String fields = err.getFields();
                // How do I get the value of Key_Field__c ?
            }
        }
    }
}

Because I need to know which record failed, so it can be re-processed manually

Question

To recap: How to I get the value of a custom field on the Platform Event, via the Database.SaveResult or Database.Error objects?

2
  • It would seem that the publish call and the result would normally be in the same method, so you can simply reference event.Key_Field__c. Is there some circumstance where the result is in a different method? Commented Jul 15, 2020 at 3:31
  • @MikeLockett - good point, my example was too simple, IRL there are multiple records. I will update example
    – Robs
    Commented Jul 15, 2020 at 10:27

1 Answer 1

1

I know this isn't exactly what you're looking for, but I don't see a way to get the data from the error.

I believe the results come back ordered properly, in which case, something like this should work:

void createEvents() {

    List<My_Custom_Event__e > events = new List<My_Custom_Event__e>();
    events.add(new My_Custom_Event__e(Key_Field__c = 'key field value 1'));
    events.add(new My_Custom_Event__e(Key_Field__c = 'key field value 2'));
    publishMyEvents(events);
}

void publishMyEvents(My_Custom_Event__e events) {
    Integer i=0;
    Database.SaveResult[] results = EventBus.publish(events);

    for (Database.SaveResult result : results) {
        if (result.isSuccess() == false) {
            for (Database.Error err : result.getErrors()) {
                String statusCode = err.getStatusCode();
                String message = err.getMessage();
                String fields = err.getFields();                
            }
            // How do I get the value of Key_Field__c ?
            // this shouldn't need to be in the inner loop
            events[i].Key_Field__c; 
        }
        i++;
    }
}

It might make sense to return a String[] of failed Key Fields.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .