I wrote this code in a trigger so addError works fine, but when code fails within a try-catch block i expected my addError message but i getting a error as i not using the try-catch.

public with sharing class triggerHandler{

public static void afterUpdate(List<Opportunity> Trigger.new)
    CustomObject__c ob = [SELECT id, name, code__c from CustomObject__c where Opportunity__c In :(Trigger.new) ];
    ob.code__c = 12345;

        update ob;
    }catch(DmlException e){
        for(Oppotunity opp : Trigger.new){
          opp.addError('Show a error');

But i getting an error like: We hit a snag. Review the errors on this page. OppotunityTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0J1w000006574PEA2; first error: Your code number is wrong.

my issue is i expected "Show a error" message when i got a DmlException because is within catch but i getting the whole exception message.

sorry my english help please!!

  • 1
    Does this answer your question? Does addError() work outside of triggers?
    – Phil W
    Apr 3, 2020 at 11:30
  • 1
    Note that this question is badly written as it doesn't explain the context of what you are doing. I suggest you edit it to add more detail. You can see by my answer that it is very ambiguous.
    – Phil W
    Apr 3, 2020 at 11:41
  • 1
    This code has numerous syntax errors and will not compile.
    – David Reed
    Apr 3, 2020 at 13:06
  • Some other code in your OpportunityTtigger handling is throwing the "code number" error so you need to search for that in your code base, in addition to reviewing Phil's answer. Apr 3, 2020 at 15:12
  • @DavidCheng you right the trigger is throwing the error from another block
    – wi river
    Apr 7, 2020 at 15:07

1 Answer 1


This code fundamentally misunderstands the SObject.addError and Trigger.new variable access if this code is not in a trigger - these are only for use in a trigger. See this question for details.

Showing an error back to the user may be handled in various different ways. An example for Visualforce is to use ApexPages.addMessage. Your question doesn't provide the context, so I don't know if this is an appropriate approach.

If this code is in a trigger for Opportunity after update, then the opportunity object will be locked as you are in the after phase. You could try switching to before phase instead? Take a look at the trailhead for triggers.

Note, too, that you can use Database.update with allOrNothing as false if you want to allow some of the data to be updated whilst getting details of the errors for those objects that cannot be updated as part of the result details.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .