After examining docmentation I have began to create a platform event from Apex, but I have 3 unanswered questions when it comes to the creation of platform events concerning unsuccessfull publishing of a platform event.
For creation of a platform event, you can use the EventBus Class and the publish(events) method – which returns a database.saveresult. "The EventBus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation". Based on this statement, one might wonder:
- Because this is a database.saveresult, which can return a boolean 'saveResult.isSuccess', you can suspect that the creation of a platform event could also fail. What could cause a creation of a platform event to fail?
- The saveresult is by default 'all or nothing', analogue to a database.Saveresult: "The EventBus.publish() method doesn’t throw exceptions caused by an unsuccessful publish operation. It is similar in behavior to the Apex Database.insertmethod when called with the partial success option." Why would this be an 'all or nothing'? To me it doesn't make sense, since you'd always want all platform events to succeed and if they do fail, I want an exception or at least I want to know which events failed to be created and why.
Should I cater for the failing of the creation of platform events in my code? Or is this most likely to never happen? I could throw an exception or show the situations (records in this case) for which the event creations failed to an admin.
Thanks in advance for your help!
Best Answer
You can actually find this on Platform Event Error Status Codes which lists down the reasons for the failures. And it seems there are primarily only two of such scenarios where it could fail.
For your other question:
The
Event.publish()
does return if a publish failed:This is also mentioned in the status code docs as referred above.
As for handling the exceptions, I think as long as you do not really hit the aforementioned limits or platform issues, you should be fine. But still if you want to, you do have a way to know if the publishing failed or succeeded.