20

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?

1
  • did you try maybe to send an email from within the catch? with the data you need?
    – Saariko
    Commented Sep 18, 2012 at 12:12

6 Answers 6

12

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.

7
  • 1
    I tried that and it also results in a full rollback. no data is stored. simple example: trigger TestException on Account (before insert, before update) { try { Account a; a.name = 'xxx'; } catch (Exception e) { for(Account a : trigger.new) { a.addError(e.getStackTraceString()); } DebugLog__c dl = new DebugLog__c(); dl.Log__c = e.getStackTraceString(); insert dl; } }
    – eto
    Commented Sep 29, 2012 at 19:51
  • Wow, you're right. That's unexpected and undocumented. I'll open a case with salesforce Monday (I have partner premier support so I actually get the skilled support team who can answer about this). I'm not sure if that's an apex bug, or an undocumented "feature" that if no records success to rollback the whole trigger context. Commented Sep 29, 2012 at 20:27
  • did you ever receive some feedback?
    – eto
    Commented Dec 17, 2012 at 15:35
  • Forgot about this, just opened case 08522717 on this. Commented Dec 18, 2012 at 17:28
  • 1
    Regarding the exceptional case, I believe this is basically the same issue I describe in salesforce.stackexchange.com/questions/23462/…. What happens is that when you use the Database methods, if any of the records fail, that whole operation will roll back and the system will try again ONLY with those records that succeeded. For example, if you try inserting 5 records with Database.insert and 2 of them fail, the initial insert will be rolled back and a second one will occur with only 3 records.
    – ceiroa
    Commented Jan 8, 2014 at 19:59
5

There is a very good wiki page on Developerforce.com on Exception handling. There you can see how to use email notifications on errors or even write an error record to a custom object.

http://wiki.developerforce.com/page/An_Introduction_to_Exception_Handling

3
  • that only works if I catch the exception in the trigger and allow the (probably invalid data) to be stored.
    – eto
    Commented Sep 19, 2012 at 10:36
  • you can re throw any caught exception, eg: ..}catch(Exception e) { throw e; } Commented Sep 24, 2012 at 1:34
  • when I rethrow the exception, the data will not be stored and the email will not be sent.
    – eto
    Commented Sep 29, 2012 at 18:33
3

Summer '17 now has Platform Events.

One of the interesting details about Platform Events from the docs:

Platform Events and Transactions
Unlike custom objects, platform events aren’t processed within database transactions in the Force.com platform. As a result, publishing platform events can’t be rolled back. Note the following:

  • The allOrNoneHeader API header is ignored when publishing platform events through the API.
  • The Apex setSavepoint() and rollback() Database methods aren’t supported with platform events.

Note the "can't be rolled back" part. Even if your top level transaction rolls back due to an exception you can still publish an event.

The pattern would look something like:

trigger ProblemTrigger on Account (before insert) {
    try {
        // ... trigger.new ... throws Exception
    } catch (Exception ex) {
        List<DebugDetails__e> errorMessages = new List<DebugDetails__e>();
        errorMessages.add(new DebugDetails__e(message__c = ex.getMessage()));
        List<Database.SaveResult> results = EventBus.publish(errorMessages);
        // Might need to handle railed publishing results
        throw ex; // Rethrow syntax?
    }

}


trigger CaptureDebugTrigger on DebugDetails__e (after insert) {    


    // Iterate through each notification.
    for (DebugDetails__e event : Trigger.New) {
        System.debug('Debug: ' + event.message__c);
        // Queue insert of the persistent object with the message details.
    }        
    // Insert the collection of error objects.
}

So you could publish and event with the required information and have a corresponding Apex trigger subscribed to the event to store the persistent message.

2

I would've thought handling the exception should let you insert into a log object in the finally block

Boolean exceptionOccured= false;
try{
//do something
}
catch(Exception ex){
exceptionOccured=true;
throw ex;
}
finally{
If(exceptionOccured)
//log exception XML}      }
1
  • Per my answer it does... but if every sObject in the triger context has an error your logging is also rolled back. Bug? Feature? Not sure. Commented Sep 30, 2012 at 2:21
0

If an exception is thrown in your code and you do not attempt to catch it, then SF will roll back the transaction and throw away any data inserted up until the exception is thrown.

On the surface, the behaviour you want is the somewhat unintentional side effect of not handling the transaction failure in the best manner.

I agree with the earlier comment, which is that if the exception is infrequent then catching the exception and sending an email with debug info would be the best thing to do.

0

And so you've found the reason why external "cloud" logging sites exist. Loggly.com and others like it live to serve us. Some exceptions can't be caught and all changes are rolled back in SFDC. The only log possibilities are email and cloud logging like loggly.com. Loggly.com is free for low volume accounts.

3
  • 1
    Can you demonstrate how you would use loggly.com to log an error from within a trigger when the transaction is rolled back?
    – Mark Pond
    Commented Jan 8, 2013 at 21:41
  • @MarkPond you can't as future calls and sendEmail calls are also rolled back when the trigger fails to commit any rows. While loggly looks awesome it doesn't really help in this case. Commented Jan 9, 2013 at 3:18
  • @ca_peterson, I concur... just wanted to document that conclusion within this context. I agree loggly looks like a very cool log management SaaS app.
    – Mark Pond
    Commented Jan 9, 2013 at 5:55

You must log in to answer this question.

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