Sub topic 6
Triggers, addError, and failing the whole save
This chapter covers how triggers take part in a transaction, what addError does to a save, and how that interacts with all-or-none and partial-success DML. It assumes you can read basic Apex, run insert and update statements, use try/catch with DmlException, and know that governor limits exist.
Triggers run inside the caller's transaction
A trigger is not a separate transaction. When you run insert acct;, the platform runs before triggers, validates the record, saves it, and then runs after triggers. All of that happens inside the transaction that contains your DML statement.
Two consequences follow from this:
- Work done in a trigger, such as inserting a child record, belongs to the same transaction as the statement that fired it.
- An exception thrown in a trigger propagates back to the DML statement that fired it, and from there to the code that issued that statement.
The following diagram shows the order of events for one insert that fires a trigger.
What addError does
addError is a method on sObjects and on fields. It marks a record, or one field of a record, as failed with a message. It does not throw an exception in your trigger, so the trigger code keeps running after you call it. The record is not saved.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.Email == null) {
c.addError('Email is required');
}
}
}Calling addError in the trigger above marks each Contact without an email as failed. What happens next depends on how the DML statement was issued.
With a plain DML statement
A statement such as insert contacts; is all-or-none. If any record in the list has an error, the whole statement fails. The platform throws a DmlException to the caller, and no record from that statement is saved, including records that had no error.
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(e.getMessage());
}
// Neither Contact is saved.The exception message includes the text you passed to addError.
With Database methods and allOrNone set to false
If the caller uses Database.insert(contacts, false), the failure is limited to the records that have errors. The valid records are saved, and each failed record reports its message through a Database.SaveResult.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Has Email', Email = '[email protected]'),
new Contact(LastName = 'No Email')
};
Database.SaveResult[] results = Database.insert(contacts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(contacts[i].LastName + ': ' + err.getMessage());
}
}
}In this run the first Contact is saved and the second is reported as failed with "Email is required".
| Caller | Record has `addError` | Other records in the same statement |
|---|---|---|
| `insert list;` | Statement throws `DmlException` | None are saved |
| `Database.insert(list, true)` | Statement throws `DmlException` | None are saved |
| `Database.insert(list, false)` | Failure is reported in `SaveResult` | Valid records are saved |
Where addError is allowed to work
addError is most useful in before triggers, where you validate data before it is written. You can also call it in after triggers on records in Trigger.new or Trigger.old, but only the records in the trigger context. In an after trigger, Trigger.new records are read-only, so you can mark them with addError but you cannot change their field values.
You can also call addError on a record that is not in the trigger context, for example on a record you queried yourself. The error is then attached to that record object, and it only has an effect if that same object is part of the DML statement being processed.
Field-level errors
Passing a message to a field attaches the error to that field. Field-level errors appear next to the field in Salesforce UI pages. Use this when the problem belongs to one field.
trigger OpportunityTrigger on Opportunity (before insert, before update) {
for (Opportunity o : Trigger.new) {
if (o.Amount != null && o.Amount < 0) {
o.Amount.addError('Amount cannot be negative');
}
}
}A field-level error fails the record in the same way as a record-level error. Only the place where the message is shown changes.
Throwing an exception from a trigger
You can also throw an exception in a trigger instead of calling addError. An uncaught exception in a trigger fails the whole DML statement, no matter how many records were in it, and all of its changes are undone. Unlike addError, it is not per record. Even Database.insert(list, false) will not save the other records, because the exception is not a record-level error.
| Technique | Scope of failure | Works with `allOrNone = false` |
|---|---|---|
| `record.addError(msg)` | That record (or the whole statement if all-or-none) | Yes, other records can save |
| `throw new MyException(msg)` in trigger | The whole statement, and the transaction if unhandled | No, the exception propagates |
Prefer addError for validation. It gives you per-record messages and works with partial success.
What gets undone when a trigger fails the save
When a statement fails because of a trigger, the platform undoes the changes made by that statement, including changes made by the trigger itself, such as child records it inserted. If the exception reaches the end of the transaction unhandled, the entire transaction rolls back, as covered in the earlier chapters on automatic rollback.
If your calling code catches the DmlException, the situation is the one covered in the chapter on handled exceptions. The failed statement is undone, but DML from earlier statements in the same transaction is still pending and will be committed when the transaction ends. A savepoint is the tool for undoing that earlier work too.
insert new Account(Name = 'Earlier work');
try {
insert new Contact(LastName = 'No Email'); // ContactTrigger calls addError
} catch (DmlException e) {
System.debug('Contact failed: ' + e.getMessage());
}
// 'Earlier work' is still committed when the transaction ends.Common mistakes
- Expecting
addErrorto stop the trigger. It does not exit your code. Addcontinueor restructure the loop if the rest of the logic should be skipped for that record. - Assuming partial success always applies. It applies only when the caller passes
false. Triggers cannot choose this. The caller decides. - Using
addErrorfor a record outside the DML. The error has no effect unless that object is part of the statement being processed. - Doing expensive work before validation. In a before trigger, validate first so failing records do not cost callouts or queries.
Related behavior in tests
Because addError makes a statement fail with a DmlException, you can test a validation trigger by catching that exception and asserting on the message.
@IsTest
private class ContactTriggerTest {
@IsTest
static void missingEmailIsRejected() {
Boolean failed = false;
try {
insert new Contact(LastName = 'No Email');
} catch (DmlException e) {
failed = true;
System.assert(e.getMessage().contains('Email is required'));
}
System.assert(failed, 'Expected the trigger to reject the record');
}
}Exercise
A trigger calls addError on one Contact in a list of five. The caller runs Database.insert(contacts, false). How many Contacts are saved, and how does the caller find out about the failure?
Show answer
Four Contacts are saved. The record with the error is not saved, and the caller finds out by checking isSuccess() on the matching Database.SaveResult and reading its errors with getErrors().
Exercise
The same trigger throws an unhandled custom exception instead of calling addError, and the caller runs Database.insert(contacts, false). Are the other four Contacts saved?
Show answer
No. A thrown exception fails the whole DML statement, so none of the five are saved. Partial success only covers record-level errors such as those from addError.
Exercise
Your code inserts an Account, then inserts a Contact inside a try/catch. The Contact trigger calls addError, and the catch block only logs the message. Is the Account saved?
Show answer
Yes. The failed Contact statement is undone, but the exception was caught and the Account insert is still part of the transaction, so it is committed when the transaction ends. To undo the Account too, set a savepoint before the first insert and call Database.rollback in the catch block.