[SalesForce] Show error message from custom exception on standand page in trigger handler

I am writing a trigger in which I want to throw a custom exception to display only the exception message instead of all the details. I cannot use addError() method because its not on trigger context variable, I am passing ids of records to the trigger handler method and fetching them again to use them, this is required for me as I am using same handler for 4 different SObjects.

The output that I am getting is as below

In the above exception thrown on the page, I just want to show error message as 'Other Sales Rep is not found for bundled Opportunity with Id 00kn0000003lKllAAE' instead of all other details.

Exception class,

public class TriggerException  extends Exception {}

Code used to throw exception from trigger handler.

throw new TriggerException (
                    ' Other Sales Rep is not found for bundled Opportunity with Id ' + currentOppLineItem.Id);

is there any way to achieve this?

Any type of help is much appreciated.

Best Answer

Try the Id.addError method, which will work as long as you know the Id of the Opportunity that should show this error. I'm assuming you can pull it from currentOppLineItem:

Id parentId = currentOppLineItem.OpportunityId;
parentId.addError('<Message goes here>');

Your idea that you cannot call addError to map back to the source records is not correct. Even with SObject.addError you could do it, as long as you saved the trigger context records in your state somewhere.

If you are not willing or able to figure out addError, you need to catch the error you've thrown and add it to the page.

try
{
    // operation that throws
}
catch (TriggerException tex)
{
    ApexPages.addMessages(tex);
}
Related Topic