[SalesForce] Handle exception in managed package

What are the different approaches to handle exceptions inside a managed package? Just a brief heads up would be really helpful.

From my research, I understand that it is not possible to get the stacktrace inside a manged package. All we can do is

  1. Log in to the subscriber org (through LMA) when there is an issue and check the debug log
  2. Contact salesforce support to see the debug logs
  3. Not handle the exceptions and let the exception be emailed to the developer (which I agree is very bad)
  4. Store the error message alone in a custom object (stacktrace wont be available)

Winter'12 release just enables ISVs to check the debug log through LMA. We have a managed package that is not available in appexchange. So LMA is out of question.

The 4th approach seems to be more apt. Along with the error message captuirng the class name/method name could be helpful. If a customer reports any problem, we could potentially check the custom object and try to understand what might have gone wrong.

Currently, the exception handling code in our managed package tries to catch specific exceptions like DMLException, ListException and we are logging it in a custom object. For unknown exceptions, all we capture is just an error message and then we will have to figure out what could have gone wrong in the try block.

Example code

try {
    // Line 1 where a list exception could occur
    // Line 2
    // Line 3
    // Line 4
    // Line 5 where a DML Exception could occur
} catch(DMLException e) {
    // Log the e.getMessage() in custom object along with class name
} catch(ListException e) {
    // Log the e.getMessage() in custom object along with class name
} catch(Exception e) {
    // At this point the eception could have occured anywhere from line 2 to line 4
    // But we just store the error message and try to decipher what could have gone wrong
}

Best Answer

There is a lot more information you can obtain from the exception object. Look here for details:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_exception_methods.htm

Especially these methods should come close to your needs:

  • getStackTraceString
  • getLineNumber
  • getCause
  • getMessage

The methods should work well just for unspecified exceptions like this

try { 
    //...
} catch(Exception e) {
    string msg = e.getStackTraceString();
    // write to DB
}

But don't be over enthusiastic. In my experience logging into a custom object works great in some situations and not at all in others. Biggest challenge for me is this

Exception: :System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

Related Topic