3

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

Thanks

1 Answer 1

5

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');
    }
    EventBus.publish(logs);
}

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

3
  • Great! let me try this out and come back! Commented Mar 22, 2018 at 8:40
  • Will both triggers work in before event? Commented 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
    Commented Mar 22, 2018 at 10:17

You must log in to answer this question.

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