Sub topic 11
Rejecting records with addError
This chapter assumes you can write a basic trigger, know the seven trigger events, and can read Trigger.new, Trigger.old and Trigger.oldMap. It also assumes you already follow the bulk rules: no SOQL or DML inside loops.
What addError does
addError is a method on SObject records and on their fields. It attaches an error message to a record during a trigger. When the trigger finishes, Salesforce sees the error and refuses to save that record. The user sees the message in the UI. API callers get it in the response, and Apex callers get it in a Database.SaveResult or a DmlException.
Two facts shape how you use it:
addErrordoes not stop your code. It records the error and returns, so the rest of the loop body still runs. Usecontinueif you don't want more logic to run on a failed record.- It only works on records the trigger is processing: the records in
Trigger.neworTrigger.old. Calling it on a record you queried yourself has no effect on the save.
Record-level and field-level errors
There are two forms you will use in practice.
| Form | Example | Where the user sees it |
|---|---|---|
| Record-level | `a.addError('Message')` | At the top of the page layout |
| Field-level | `a.Name.addError('Message')` | Under that field, and highlighted |
Use the field-level form when the problem belongs to one field. The user then sees which field to fix. Use the record-level form when the rule involves several fields or the whole record, as in a delete guard.
trigger OpportunityCloseRules on Opportunity (before insert, before update) {
for (Opportunity opp : Trigger.new) {
if (opp.StageName == 'Closed Won') {
if (opp.Amount == null || opp.Amount <= 0) {
opp.Amount.addError('Amount is required when an opportunity is Closed Won.');
continue;
}
if (String.isBlank(opp.NextStep) == false) {
opp.NextStep.addError('Clear Next Step when an opportunity is Closed Won.');
}
}
}
}The continue after the first error skips the second check for that record. Without it, one record could collect several messages. That is sometimes what you want, so choose deliberately.
Validation in before triggers
A before trigger is the usual place for validation. The record has not been written yet, so rejecting it costs little. The before-delete guard below checks for open opportunities in one query and then rejects the matching accounts.
trigger AccountDeleteGuard on Account (before delete) {
Set<Id> accountsWithOpenOpps = new Set<Id>();
for (AggregateResult ar : [
SELECT AccountId acctId
FROM Opportunity
WHERE AccountId IN :Trigger.oldMap.keySet()
AND IsClosed = false
GROUP BY AccountId
]) {
accountsWithOpenOpps.add((Id) ar.get('acctId'));
}
for (Account a : Trigger.old) {
if (accountsWithOpenOpps.contains(a.Id)) {
a.addError('This account has open opportunities and cannot be deleted.');
}
}
}Delete events have no Trigger.new, so the loop reads Trigger.old. The query runs once for the whole batch of up to 200 accounts. Only the loop body decides which records fail.
addError in after triggers
You can also call addError in an after trigger, even though field values on Trigger.new are read-only there. The record then fails and the DML is rolled back, including any changes made earlier in the same statement.
Choose an after trigger for validation only when you need something that exists after the save, such as the record Id or a value calculated by the platform. Otherwise prefer a before trigger. An after trigger does the work first and undoes it afterward.
trigger ContactLimitPerAccount on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acctId'), (Integer) ar.get('total'));
}
for (Contact c : Trigger.new) {
Integer total = counts.get(c.AccountId);
if (total != null && total > 10) {
c.addError('An account can have at most 10 contacts.');
}
}
}The count query runs after the insert, so it already includes the new contacts. That is why this check lives in an after trigger.
What happens to the rest of the batch
Whether other records in the same batch are saved depends on how the DML was issued.
- All-or-none (the default for
insert,updateanddeletestatements in Apex): if any record has an error, the whole statement fails and nothing is saved. - Partial success (
Database.insert(records, false), or API calls withallOrNoneset to false): records with errors are rejected and the others can be saved. Salesforce may run the trigger again on the remaining records, so your logic must be safe to run more than once on a batch.
Because of this, never assume that an error on one record is the only effect of your trigger. Treat the batch as the unit of work.
addError versus throwing an exception
You could stop a save by throwing an exception, but addError is usually better.
| Approach | Effect |
|---|---|
| `record.addError(...)` | Fails only the flagged record under partial success. Message is tied to the record or field. |
| `throw new MyException(...)` | Fails the whole transaction. In the UI the user may see a generic message with a stack trace. |
Reserve exceptions for conditions that are bugs or unrecoverable states, not for business rules about individual records.
Testing a rejection
Test the failure path as well as the success path. Database.delete(record, false) returns a SaveResult-style result instead of throwing, so you can assert on the message.
@IsTest
private class AccountDeleteGuardTest {
@IsTest
static void blocksDeleteWithOpenOpportunity() {
Account acct = new Account(Name = 'Guard Test');
insert acct;
insert new Opportunity(
Name = 'Open Opp',
AccountId = acct.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
);
Database.DeleteResult result = Database.delete(acct, false);
System.assertEquals(false, result.isSuccess());
System.assert(
result.getErrors()[0].getMessage().contains('open opportunities'),
'Expected the open opportunity message'
);
System.assertEquals(1, [SELECT COUNT() FROM Account WHERE Id = :acct.Id]);
}
}With a plain delete acct; the test would need a try/catch for DmlException. The Database method keeps the assertion simpler.
Common mistakes
- Using addError on a queried record. Only the records in
Trigger.neworTrigger.oldare tied to the save. Errors on other copies are ignored. - Forgetting that code continues. Updates or DML after
addErrorstill run for that record, unless you usecontinue. - Reading
Trigger.newin a delete trigger. It is null on delete. UseTrigger.old. - Querying inside the loop. Validation rules that need related data should gather Ids first, query once, and look results up in a map or set.
- Validating in an after trigger without need. It works, but it wastes the work that gets rolled back.
Exercise
An after insert trigger on Contact calls c.addError('Too many contacts') for one record in a batch of 50 that was inserted with insert contacts;. What happens to the other 49 contacts, and how would the result differ if the code used Database.insert(contacts, false)?
Show answer
With insert contacts; the statement is all-or-none, so the error on one record causes the whole statement to fail and a DmlException is thrown. None of the 50 contacts is saved. With Database.insert(contacts, false) partial success is allowed, so only the flagged contact is rejected, its error appears in the matching SaveResult, and the other 49 can be saved. The trigger may also run again on the remaining records, so its logic must be safe to repeat.
Exercise
Why does the open-opportunities delete guard read Trigger.old and use Trigger.oldMap.keySet() instead of Trigger.new?
Show answer
Delete events have no new version of the records, so Trigger.new is null. Trigger.old holds the records being deleted and Trigger.oldMap is keyed by their Ids, which gives the Set needed for a single bulk-safe IN query.