[SalesForce] Database.SaveResult with Try/Catch

I have been working on trigger, and using Database.SaveResult with addError to show error on the UI. However, Database.saveResult handle all the DML Exceptions. If some other exception what is the best way to display that on UI.

 Imagine below in the trigger context

        try {

           Integer i = 5 * null    // this will cause an math exception****  

           Database.saveResult[]  srList = Database.update(listToUpdate, false);     
            // Doing all the addError business here to show error and stop  transaction. 
Doing .addError here to show custom error message

          } catch(Exception E){
             How to show this exception in the UI with custom error message. 
I have tried customException but that has line number and other extra stuff.
         }

Best Answer

In theory, you should never use try-catch in a trigger context. If an exception occurs, you want it to reach the outer layer, whatever that may be (it could be the UI, an API call, etc). All of your code should be written in a way that will never generate an exception, and given the limitations of what's possible in triggers (e.g. you can't do callouts), there's no good reason[citation needed] for using a try-catch in a trigger.

NOTE: There are actually a few real reasons why you might want to catch an exception, like Messaging.reserve(Single/Mass)EmailCapacity, which has no way of communicating that you've reached your limits except by throwing an exception, but generally you'd want to convert that to a normal addError message instead.

Related Topic