How to Add a Custom Error in a Salesforce Trigger using addError()
What does it mean
Using addError()
in a Salesforce trigger means you are intentionally stopping a database operation (like insert, update, or delete) for a specific record.
When addError()
is called, Salesforce cancels the requested action for that particular record and displays a custom error message to the user in the interface or returns it as an exception via the API.
This technique is commonly used to enforce complex validation rules that cannot be handled by standard Salesforce validation rules.
Solution
Identify the specific record in the trigger context for which the error condition is met.
Use the addError()
method on that SObject record instance.
You can add a general error message to the record using recordInstance.addError('Your custom error message here.');
.
To associate the error with a specific field on the record, use recordInstance.FieldName__c.addError('Error message for this field.');
.
Place this code within a conditional block (e.g., an if
statement) that checks for the condition that should trigger the error.
addError()
is most effective in "before" triggers (before insert
, before update
, before delete
) as it prevents the record from being saved to the database.
Here''s a simple example for a before insert
trigger on the Account object:
trigger AccountTrigger on Account (before insert) {
for (Account acc : Trigger.new) {
if (acc.Name == null || acc.Name == '') {
acc.addError('Account Name cannot be blank.');
}
}
}
Why it happened
The addError()
method is an Apex SObject method designed specifically for triggers.
When invoked on an SObject record within a trigger context, it flags that record as having a validation failure.
Salesforce''s DML engine processes these flags after the trigger execution completes but before the database commit.
If any record in the DML operation has addError()
called on it, the entire transaction for those records is rolled back, and the error message(s) are returned.
This mechanism allows developers to implement server-side validation logic beyond the capabilities of declarative tools.