function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DaveHagmanDaveHagman 

Best way to inform a user when an error has occurred

Hi all,

 

I was doing some research to try and find the best (In this case "best" means easiest to read) way to provide an error message to a user . I have a trigger where I want to display a clear error message to the user if a defined maximum has been reached. When you throw an exception a long very confusing looking error message is displayed to the user detailing the trigger name, line number of the error etc. I really only want to display the exception's message, not all of the other details. Is there any way to do this? If not, what are other methods of informing the user that an error has occurred? Is there any way to call a message box from a trigger? I know I can use java script when the action is tied to a button to display a message box but this is a trigger, not a class. 

Best Answer chosen by Admin (Salesforce Developers) 
Cory CowgillCory Cowgill

You use the addError() method on the SObject that you are manipulating in your trigger. Take a look at the link I provided, it has a try/catch example.

 

If you use the addError() method you will not get the extra information (trigger, line number, etc), only what you put into the addError() method.

 

 

All Answers

Cory CowgillCory Cowgill

In an Apex Trigger context, you can add error messages to the object which will be thrown back to the UI.

 

accountRec.addError('This is an error message.');

 

In an Apex Controller context, you can use the ApexPages Methods to add custom error messages like this:

 

ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, 'Here is a Fatal Error in Controller');
ApexPages.addMessage(myMsg);

 

Also check out this article:

 

http://wiki.developerforce.com/index.php/An_Introduction_to_Exception_Handling

DaveHagmanDaveHagman

On which object can I use the addError() method? Do I use that on the Exception class? Also, if I use the addError() method and throw the object will I still get all the extra debug information that you get when you throw a regular exception?

Cory CowgillCory Cowgill

You use the addError() method on the SObject that you are manipulating in your trigger. Take a look at the link I provided, it has a try/catch example.

 

If you use the addError() method you will not get the extra information (trigger, line number, etc), only what you put into the addError() method.

 

 

This was selected as the best answer
DaveHagmanDaveHagman

Excellent thank you very much!   :)