there is a requirment where when data is upserted in bulk from external system, we need to check for certain criteria, if it does not match, we should prevent the insert/update and log the error in custom object.

However using before trigger to prevent the upsertion does not allow error log insertion into the custom object as everything gets rolled back.Is there any other approach for the same.

We tried allowing the DML and then delete the unmatched record. HOwever in case of update we will never know which fields were updated to revert back. Any suggestions


1 Answer 1


You can now do this by way of Platform Events. Unlike normal DML operations, Platform Events are not rolled back in a transaction, even if there are failures. To use this feature, there's a few steps involved.

First, create your Log object, if you haven't already. Next, create a Platform Event that has a field (or more, if you desire). After that, add a trigger to actually create the logs. Here's an example:

// Note: __e is not a typo. It is the special extension used by Platform Events.
trigger LogErrorEventTrigger on LogErrorEvent__e (after insert) {
    Log__c[] logs = new Log__c[0];
    for(LogErrorEvent__e record: Trigger.new) {
        logs.add(new Log__c(Log__c=record.Log__c));
    insert logs;

To actually use this, you need to "publish" these events:

trigger CustomObjectTrigger on CustomObject__c (after insert) {
    LogErrorEvent__e[] logs = new LogErrorEvent__e[0];
    for(CustomObject__c record: Trigger.new) {
        logs.add(new LogErrorEvent__e(Log__c='Blocked insert'));
        record.addError('Block insert');

This will prevent inserts, updates, deletes, undeletes, whichever you would like to handle, and log the appropriate message into your log queue.

  • Great! let me try this out and come back! Mar 22, 2018 at 8:40
  • Will both triggers work in before event? Mar 22, 2018 at 10:12
  • @SFDCLearner The Platform Event trigger must be an "after insert" (read this topic), but the normal record trigger may be any of the seven supported events, including before insert.
    – sfdcfox
    Mar 22, 2018 at 10:17
  • This is an amazing solution, thanks for sharing!
    – Arthlete
    Jun 11, 2019 at 15:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.