Sub topic 6
Triggers, addError, and failing the whole save
This chapter assumes you can write basic Apex triggers, run DML statements such as insert and update, and use try/catch with DmlException. It also assumes you know that an unhandled exception rolls back a transaction, and that a single DML statement is all-or-none by default.
Triggers run inside the caller's transaction
A trigger does not start its own transaction. It runs inside the transaction of the DML statement that fired it. If the trigger fails the save, the whole DML statement fails with it.
You can fail a save in two ways:
- Throw an unhandled exception, such as a
NullPointerException. The entire transaction rolls back. - Call
addErroron a record or a field. This marks that record as failed and gives the user a clean message.
Marking a record with addError
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.Email == null) {
c.addError('Email is required');
}
}
}addError does not throw an exception, so the loop keeps running and every bad record gets its own message. Once a record has an error, Salesforce does not save it.
You can also attach the error to one field with c.Email.addError('Email is required'). The message then appears next to that field in the UI.
What happens to the other records
The effect depends on how the DML statement was called.
| DML call | One record has an error | Result |
|---|---|---|
| `insert list;` | Yes | The whole statement fails and throws a `DmlException`. No records are saved. |
| `Database.insert(list, true)` | Yes | Same as above. `true` is the default for `allOrNone`. |
| `Database.insert(list, false)` | Yes | Valid records save. The failed record is reported in its `SaveResult`. |
In an all-or-none statement, one addError fails every record in that statement. The rollback covers the whole statement, not only the bad record.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Has Email', Email = '[email protected]'),
new Contact(LastName = 'No Email')
};
try {
insert contacts;
} catch (DmlException e) {
System.debug('Nothing saved: ' + e.getMessage());
}With the trigger above, the second contact has no email, so neither contact is saved.
Seeing the failure in a partial-success call
If the caller uses Database.insert(contacts, false), the same trigger gives a different outcome. The first contact is saved. The second contact appears in the results with the message you passed to addError.
Database.SaveResult[] results = Database.insert(contacts, false);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
System.debug(sr.getErrors()[0].getMessage());
}
}The trigger code is unchanged. The caller decides whether one failure sinks the whole statement.
Limits of addError
addError works on records in the current trigger context, which means Trigger.new in before triggers and after triggers. It affects only the DML statement that fired the trigger. Work done earlier in the same transaction by other statements is not undone unless the error becomes an unhandled exception. If the caller catches the DmlException, that earlier work stays and will commit. This is the same rule you saw for caught exceptions.
Exercise
A trigger calls addError on one Account in a list of 10. The caller runs insert accounts; inside a try/catch that catches DmlException. How many of the 10 accounts are saved, and how many would be saved if the caller used Database.insert(accounts, false)?
Show answer
With insert accounts;, none of the 10 are saved, because the statement is all-or-none and the DmlException is thrown. With Database.insert(accounts, false), 9 are saved, and the failed account is reported in its SaveResult.