Can I store information even if the trigger throws an exception?

I currently have a trigger which sometimes fails when new information is inserted from a 3rd party system. I can’t simply check the logs as it usually happens during the night and it’s not easy to spot the reason (pretty complicated code). Therefore I tried to add some enhanced debugging which stores valuable information into a custom object and then inserts this into the database.

This unfortunately only works if I catch the exception. As I would prefer the system to still throw an exception if such a weird situation happens I search for a way to store my debug for later research.

I already tried with @future but even these methods do not get called if I have an exception in the trigger.

Any ideas how I can log data from a trigger for later inspection although the trigger throws an exception?

Answer

As you’ve noticed if an apex script throws an unhandled exception everything it did is rolled back: @future, emails, DML, etc.

The good news is that there is a way to prevent a DML operation from succeeding without causing the whole apex transaction to be rolled back (except in the specific case mentioned below): the sObject.addError method. If you call this method on every sObject in your trigger it will prevent them all from being committed to the database, however any other DML operations you perform (that of course, do not cause errors in their own triggers) will be committed successfully.

If you’re looking to log to a custom object this is your best bet; catch the exception, mark everything in Trigger.new with addError, then commit your log sObject.

EXCEPTION – To summarize the edits from subsequent contact with salesforce: this will not work if every record in the trigger has errors. In this case all work done in the trigger, including @future method calls, sending email, queueing batch jobs, or performing any DML, is rolled back.

I opened a Salesforce case with partner premier support (who actually troubleshoot apex issues!) #08522717. Salesforce claims this is working as designed, and pointed me to the wiki. Which seems to suggest that setting the all or nothing flag will impact this behavior but in my testing it didn’t matter – if no DML rows commit without errors all operations are rolled back.

Attribution
Source : Link , Question Author : iwerstler , Answer Author : ceiroa

Leave a Comment