6

If I am running some Apex code that generates an uncaught exception, everything is rolled back automatically - changes to records, sent emails, future tasks, etc.

Is there anything that does not get rolled back?

The reason I am asking is because I wish to provide an audit log of operations (even unsuccessful ones). Obviously there is the debug log, but that only appears if enabled, doesn't handle managed packages very well, and no longer appears for Sites guest users unless you jump through hoops (which isn't always possible).

2
  • 1
    The obvious solution is to catch the exception.
    – Adrian Larson
    Feb 14, 2017 at 17:02
  • Although you would be out of luck for the exceptions that can't be caught.
    – martin
    Feb 15, 2017 at 6:26

2 Answers 2

2

You might be knowing that we can handle different kind of exceptions using a try catch statement. With that you can collect different logs in a custom object.

// Set save point
Savepoint sp = Database.setSavepoint();

// custom object used for logging
Logging__c objLogging = new Logging__c();
try{
     //Your code here

     objLogging.description = 'inside try statement';
} catch (ListException e) {
     //Optional catch of a specific exception type
     //Specific exception handling code here

     objLogging.description += 'List exception: ' + e.getMessage();
} catch (Exception e) {
     //Generic exception handling code here

     objLogging.description += 'generic exception: ' + e.getMessage();
} finally {
     //optional finally block
     //code to run whether there is an exception or not

     // Rolling back to previous state!
     Database.rollback(sp);
     // log the error into custom object
     insert/update objLogging;
}

Additionally you may want to use Database.rollback for having a more controlled rollback mechanism.

2
  • 1
    I would suggest implementing a Savepoint and rolling back prior to updating the log maybe??.
    – Eric
    Feb 14, 2017 at 17:22
  • You're right, i didn't add it to answer, had just the link. Thanks added!
    – Raul
    Feb 14, 2017 at 17:52
0

The short answer to your question is that uncaught exceptions can't be logged. It is a best practice to wrap your code in try/catch blocks. You can even wrap large sections of code in a try and even nest try/catch blocks within an existing try block.

Developerforce has a very comprehensive article on exception handling

1
  • 1
    N.B. for triggers invoked from, say, the standard UI, if you catch an error, you can't fail the transaction and log the error
    – cropredy
    Feb 15, 2017 at 1:16

You must log in to answer this question.

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