Display Custom Error Messages in Salesforce Apex (addError Method Explained with Examples)

In Salesforce, maintaining data quality is very important. When users enter incorrect or invalid data, the system should stop them and show a clear error message.

Salesforce provides basic validation rules, but sometimes we need more control to handle complex business logic.

In such cases, Salesforce Apex helps us display custom error messages using the addError() method. This method allows developers to stop record saving and show meaningful error messages directly on the screen.

We create validation rules in Salesforce to show errors on the record detail page. When a user enters incorrect data, the validation rule stops the save and displays an error message.

However, when working with Apex, validation rules can sometimes be insufficient. For example, we need to use Apex code to check complex conditions or compare multiple records.

In Apex, we use the addError() method to stop the record from saving and show an error message. This works like a validation rule error, but gives you more control in the code.

In this tutorial, we will learn how to display custom error messages in Salesforce Apex. I will explain how to display errors in real-time business scenarios using Apex code.

What is the addError() Method in Salesforce Apex?

The addError() method displays a custom error message in Salesforce Apex and prevents any DML operation from occurring. Another method, addError(fieldName, errorMsg), dynamically adds errors to fields of an sObject associated with the specified field name.

addError() is mainly used in Apex classesTriggersValidation logic, and Custom Business Rules to display custom error messages directly on specific fields or records.

Syntax of addError()

//sObject.addError('Error Message');

Account acc = new Account( Name=’Test Account’ );
acc.addError( ‘Name’, ‘Invalid Account Name’ ); 

record.FieldName.addError('Error Message'); // Field-level error

Here, we declare the account sObject. Then, we added an error message to the Name field using the addError() method with a custom message that we want to display.

Why Use addError() in Salesforce Apex?

We can use the addError() method for the following purposes:

  • It prevents incorrect data or values that do not match the defined condition.
  • We can display the custom error message to the user explaining why the save failed.
  • It works before the record is saved, so data quality is maintained.

Validation Rule vs addError() in Salesforce

FeatureValidation RuleaddError()
ComplexityLowHigh
LogicFormula-basedCode-based
Multiple recordsLimitedSupported
FlexibilityLimitedVery High

Real-Time Examples to Display Custom Error Messages in Salesforce Apex

Now, I will provide real-time examples of displaying custom errors in Salesforce Apex using the addError() method to display a custom error message on the field or record page.

Example 1: Display Error Message at Bottom of Record Page

Let’s take an example: We have created an account record in the account object. If we try to change the account number field value of that existing account record, we need to throw an error message.

We checked the old and new account record IDs in the Apex trigger below. If the new account number is not equal to the old one, then it has been changed. So, here, we want to prevent that record from being saved.

For that, we added the addError() method, which displays error messages in Salesforce UI and prevents records from being saved. Provide the message you want displayed when the error occurs.

After that, save the Apex trigger code to activate it.

trigger PreventFieldChange on Account ( before update ) {
    
    for ( Account oldAcc : Trigger.Old ) {
          for ( Account newAcc : Trigger.New ) {           
                 if ( oldAcc.Id == newAcc.Id   && 
                        oldAcc.AccountNumber != newAcc.AccountNumber) { 
                               newAcc .addError ( 'You cannot change the Account Number.' );
         }
      }
   }
}

Navigate to the account object tab and open any existing account record in edit mode.

Trigger.Old in Salesforce Apex

Then, change the account number and enter a different value. Click the Save button to save changes.

Trigger.Old Context Variable in Apex Trigger

As you click the save button, you will see the error message that you provided in the addError() method.

Display Custom Error Messages in Salesforce Apex

In this way, we can use the addError() method in Salesforce Apex to display a custom error message at the Bottom of the record page.

Example 2: Display Error Message on the Field

For example, if you set the opportunity amount, you don’t want any other user to change that amount, even if it is editable.

Suppose any user tries to change the opportunity amount and checks it against the new amount. If it does not match, prevent the record from being saved.

To display the error message in the field, we need to specify the field API name before calling addError().

trigger OppoTrigger on Opportunity (before update) {
    
    Map<Id, Opportunity> oppoMap = Trigger.oldMap;

        for ( Opportunity newOpp : Trigger.new ) {
                Opportunity oldOpp = oppoMap.get ( newOpp.Id );
                      if ( newOpp.Amount != oldOpp.Amount ) {
                            newOpp.Amount.addError ( 'Amount cannot be changed' );
                      }
           }
}

As you navigate to the opportunity record, you can see the number fields with the value of 4400.

Create an Apex Trigger in Salesforce

As I changed the value and tried to save the record, the error said we passed an argument to the addError() method, and the record was not saved.

Apex Triggers in Salesforce

In this way, we can use the addError() method in Salesforce Apex to display a custom error message on the field.

Example 3: Prevent Saving Account with Duplicate Phone Number

For example, we need to ensure that we do not have two account records with the same phone number for security purposes. If the user provides a duplicate number, an error message should be displayed, and the record should not be saved.

In Apex, we have created trigger code to prevent users from creating or updating an account if another account already exists with the same phone number. It uses the addError() method to show an error message and prevent the record from being saved.

trigger addErrorMethod on Account (before insert, before update) {

    Set<String> incomingPhoneNumbers = new Set<String>();
    
    for (Account acc : Trigger.new) {
        if (acc.Phone != null) {
            incomingPhoneNumbers.add(acc.Phone);
        }
    }

    Map<String, Account> existingAccounts = new Map<String, Account>();

    for (Account acc : [SELECT Id, Phone FROM Account WHERE Phone IN :incomingPhoneNumbers]) {
                           existingAccounts.put(acc.Phone, acc);
                        }

    for (Account acc : Trigger.new) {
        if (acc.Phone != null && existingAccounts.containsKey(acc.Phone)) {
            acc.Phone.addError('An account with this phone number already exists.');
        }
    }
}

In the image below, we have one account record with a phone number value.

addError Method in Salesforce Apex

Now, when we try to create a new account with the same phone number as the existing account record and click Save, we receive the error message returned by the addError() method.

addError() Method in Salesforce Apex

In this way, we can prevent users from creating an account if another account already exists for the same phone number by using the addError() method to display an error message and prevent the record from being saved.

Frequently Asked Questions

Q1: Can we use addError() in an Apex class?

Yes, but mostly used in triggers

Q2: Does addError() stop DML operation?

Yes, it prevents saving the record

Q3: Can we show an error in the field?

Yes, using the field.addError()

Q4: Is addError() better than a validation rule?

For complex logic → YES

Conclusion

I hope you have got an idea about how to display custom error messages in Salesforce Apex. I have explained the method we can use to display errors in real-time business scenarios using Apex code.

Displaying custom error messages in Salesforce Apex using the addError() method is a powerful way to enforce business rules and maintain data quality.

It offers greater flexibility than validation rules and enables developers to handle complex scenarios effectively.

By using sound logic, real-world use cases, and best practices, you can create robust validation systems that improve the user experience and prevent incorrect data entry.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.