1

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.
         }
1
  • Triggers don't always have an associated UI context. Is this a theoretical concern, or are you encountering specific errors that aren't associated to a specific sObject in the trigger?
    – David Reed
    May 3 '18 at 18:20
2

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.

3
  • Thanks and Congratulation on reaching 200K...way to go.. Yes I want to throw the error UI but with custom error message. I tried custom exception for that but it comes with line number and other stuff.. How can I show custom error message for exception ( not DML) in trigger. May 3 '18 at 18:29
  • @amidstCloud Thanks! Use addError, that's what it's there for.
    – sfdcfox
    May 3 '18 at 18:31
  • @amidstCloud In your arbitrary example, you don't want to try-catch a NPE; the purpose of the uncaught exception is to provide a stack trace so the developer can fix the problem. Using try-catch, or throwing a custom exception, is a practice that's guaranteed to cause you to pull your hair out in frustration later.
    – sfdcfox
    May 3 '18 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.