Activity Forums Salesforce® Discussions Can I store information even if the trigger throws an exception in salesforce?

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

    Posted by Deepak on October 7, 2019 at 11:00 am

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

    Laveena replied 4 years, 6 months ago 2 Members · 1 Reply
  • 1 Reply
  • Laveena

    Member
    October 7, 2019 at 12:43 pm

    Hi Deepak,

    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.

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos