2

I'm getting INVALID_FIELD_FOR_INSERT_UPDATE - The event can't be published because it contains an ID value. when logging my platform event errors like so:

private static List <Account_Change_Event__e> newaccountChangeEvent = new List <Account_Change_Event__e>();

public static void broadcastAccountEvent(Map<Id, Account> newMap, Map<Id, Account> oldMap) {
List<Account> accsToProvision = new List<Account>();
for (Account acc : newMap.values()) {
    Account oldacc = oldMap.get(acc.Id);
    if(acc.Level__c != oldacc.Level__c) {
        newaccountChangeEvent.add (
            new Account_Change_Event__e (
                    Name__c = acc.Name,
                    Level__c = acc.Level__c,
                )
        );
    }
}

if(!newaccountChangeEvent.isEmpty()) {
    List<Database.SaveResult> results = EventBus.publish(newEventsList);
    for (Database.SaveResult sr : results) {
        if (sr.isSuccess()) {
            System.debug('Successfully published a platform event.');
        } else {
            for (Database.Error err : sr.getErrors()) {
                System.debug('publish Error returned: ' +
                            err.getStatusCode() +
                            ' - ' +
                            err.getMessage());
            }
        }
    }
}

The strange parts are: 1) I'm not including an ID in the Platform Event, 2) The logs first show Successfully published a platform event. and then logs the above error 3 times in a row. It seems like it's trying to re-publish or some other behavior that's quite unclear.

2
  • You should include the rest of the code, since I don't think the error message you shared is coming from anything here. May 3, 2021 at 17:33
  • @NicholasSavini - good call, I've added comparable code, thanks!
    – McD
    May 3, 2021 at 17:40

1 Answer 1

3

Since it's in a trigger, my guess is that it's running the logic to publish the events a second time (as you suspected). Your trigger handler likely runs on the before and after events, so perhaps this logic is running both times.

A simple way to prevent this error would be to clear out the list of platform events once you publish them:

if(!newaccountChangeEvent.isEmpty()) {
    List<Database.SaveResult> results = EventBus.publish(newEventsList);
    newEventsList.clear();
    ...
}

But this is probably also a symptom of a bigger problem; the code should be protected so that it only runs one time, during the appropriate trigger event.

You must log in to answer this question.

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