Sub topic 11
Rejecting records with addError
This chapter assumes you can write a basic Apex trigger, know the before and after timing rules, and can read Trigger.new and Trigger.old. It covers how addError blocks a save and where to call it.
What addError does
addError is a method on SObject records and on individual fields. Calling it marks the record as failed. Salesforce then rolls back the DML for the failing records and shows your message to the user or returns it in the API response.
You call it on a record from a trigger collection. You do not throw an exception and you do not need a DML statement.
trigger AccountDeleteGuard on Account (before delete) {
for (Account a : Trigger.old) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.addError('High-revenue accounts cannot be deleted.');
}
}
}Delete events have no Trigger.new, so the loop reads Trigger.old. Records in Trigger.old can still call addError in a before delete trigger.
Record-level and field-level errors
Calling addError on the record shows the message at the top of the page. Calling it on a field shows the message next to that field in the UI.
trigger OpportunityAmountCheck on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount != null && opp.Amount < 0) {
opp.Amount.addError('Amount cannot be negative.');
}
}
}Use a field-level error when one field is at fault. Use a record-level error when the problem involves several fields or the record as a whole.
Where you can call it
| Trigger timing | Can call addError? | Effect |
|---|---|---|
| Before insert, update, delete | Yes | Blocks the save for that record. |
| After insert, update, delete, undelete | Yes | Rolls back the save for that record. |
In an after trigger the record has already been written inside the transaction. The error still undoes it, but other work in the transaction may have run first. Prefer before triggers for validation so you reject bad data early.
Bulk behavior
A trigger can receive up to 200 records. Calling addError on one record does not stop the loop, and the other records keep being processed. With a partial-success call such as Database.insert(records, false), only the flagged records fail and the rest can save. With a plain insert statement, the whole DML operation fails, because an unhandled error on any record fails the statement.
Common mistakes
- Escaping HTML:
addErrorescapes its message by default. Passfalseas the second argument only for trusted text, for examplea.addError(message, false). Never include user-entered values that way. - Doing validation in an after trigger when a before trigger would work. You waste work that is then rolled back.
- Calling
addErroron a record that is not in the trigger's collections. Errors apply only to records the trigger received. - Using
throwfor expected validation failures.addErrorreports per record and keeps the rest of the batch running.
Exercise
A before update trigger on Opportunity must reject any record whose StageName changed to 'Closed Won' while Amount is null. The message should appear next to the Amount field. Which collection do you loop over, and where do you call addError?
Show answer
Loop over Trigger.new. For each opportunity, compare StageName with Trigger.oldMap.get(opp.Id).StageName, and if it changed to 'Closed Won' and opp.Amount is null, call opp.Amount.addError('Amount is required to close a deal.'). Calling it on the field shows the message beside Amount.
Exercise
Why is addError in a before trigger usually better than in an after trigger?
Show answer
In a before trigger the record has not been saved yet, so you reject it early and avoid work that would be rolled back. In an after trigger the save has already happened inside the transaction and other logic may have run before the error undoes it.