Sub topic 16
What happens when something fails
This chapter assumes you can write a basic Apex trigger, know DML (insert, update, delete), and have seen validation rules and Flow. It covers what Salesforce does when any step of the save fails, and how the way you write your code changes the outcome.
The transaction is all or nothing
The whole order of execution runs inside one database transaction. The transaction covers validation, before-save flows, before triggers, the save to the database, after triggers, workflows, after-save flows, roll-up recalculation, and sharing evaluation. Until the commit step, nothing is permanent.
If an unhandled error occurs at any step, Salesforce rolls back everything the transaction did. That includes:
- the record being saved, even though the save step already ran
- records your triggers created or changed
- records changed by flows, workflow field updates, and parent saves
- the effects of earlier steps in the same request
Post-commit work never runs for a rolled-back transaction. Emails queued with Messaging.sendEmail are not sent. Queueable jobs enqueued during the transaction are discarded.
Ways an error is raised
| Source | Typical cause | Effect |
|---|---|---|
| Validation rule or required-field check | Rule formula is true, field missing | Save fails with the rule's message |
| `addError()` in a trigger | Your own business check | Marks that record as failed |
| Unhandled Apex exception | Null reference, DML failure, query on no rows | Whole transaction rolls back |
| Flow with no fault path | Failed element in a record-triggered flow | Whole transaction rolls back |
| Governor limit exceeded | Too many queries or DML statements | Uncatchable exception, full rollback |
Using addError in a trigger
addError() marks a record or field as invalid without throwing an exception. Salesforce finishes the current step for the other records, then fails the save.
trigger OpportunityCheck on Opportunity (before update) {
for (Opportunity o : Trigger.new) {
if (o.StageName == 'Closed Won' && o.Amount == null) {
o.Amount.addError('Amount is required when an opportunity is won.');
}
}
}Put checks like this in a before trigger. Nothing has been written yet, so the failure is cheap. Calling addError() in an after trigger also works, but the save has already happened and must be undone.
All-or-none versus partial success
The default DML statement (insert accts;) is all-or-none. If one record in the list fails, the statement throws a DmlException and none of the records are saved.
Database.insert(records, false) allows partial success. Records that fail are rolled back and reported. Records that pass are saved and committed.
List<Account> accts = new List<Account>{
new Account(Name = 'Good Account'),
new Account()
};
List<Database.SaveResult> results = Database.insert(accts, false);
for (Database.SaveResult r : results) {
if (!r.isSuccess()) {
for (Database.Error e : r.getErrors()) {
System.debug(e.getStatusCode() + ': ' + e.getMessage());
}
}
}The second account has no Name, so it fails with REQUIRED_FIELD_MISSING. The first account is saved.
Partial success has a side effect. Salesforce can run your triggers again for the records that did not fail. Do not assume a trigger runs exactly once per save, and do not keep non-idempotent counters in static variables without thinking it through.
Catching exceptions changes the outcome
A try/catch block lets the transaction continue after an error. This is useful but has a trap. If you catch an exception in a trigger and do nothing, the user sees a successful save while your logic silently failed.
DML that ran before the exception is not undone by catching it. To undo part of the work, use a savepoint.
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Rollback Demo');
insert a;
System.debug('Id after insert: ' + a.Id);
Database.rollback(sp);
Integer rows = [SELECT COUNT() FROM Account WHERE Name = 'Rollback Demo'];
System.debug('Rows after rollback: ' + rows);
System.debug('Id still set on the variable: ' + a.Id);
a.Id = null; // clear it before reusing the record in another insertA rollback to a savepoint has these properties:
- It undoes database changes made after the savepoint.
- It does not reset static variables, so a recursion guard set before the rollback stays set.
- It does not clear Ids on in-memory records, so inserting
aagain fails until you clear itsId. - Each
setSavepointandrollbackcall counts against the DML statement limit.
Failures you cannot catch
A governor limit exception cannot be caught. The transaction ends and rolls back, whatever try/catch blocks surround the code. Handle limits by writing bulk-safe code, not by catching errors.
Flows follow similar rules. A record-triggered flow with no fault path rolls back the transaction when an element fails. A fault path lets you handle the error, but then the transaction may continue, so decide deliberately whether to stop it, for example with a Custom Error element.
Side effects of a rollback
- Auto-number fields can skip values, because the number was consumed before the rollback.
- Callouts to external systems that already completed are not undone. Making a callout after DML in the same transaction is also restricted, with the error "You have uncommitted work pending."
- Work in post-commit steps, such as email and queued jobs, is skipped. Nothing tells the user it was skipped except the failure itself.
Exercise
A before update trigger sets a field, an after update trigger inserts a Task, and then an after-save flow throws an unhandled error. Is the Task saved? Is the original record update saved?
Show answer
Neither is saved. The error occurs before the commit, so the whole transaction rolls back, including the record update, the field change from the before trigger, and the Task. Post-commit work such as email does not run either.
Exercise
You call Database.insert(records, false) on 200 records and 5 fail validation. What happens to the other 195, and how do you find out which records failed?
Show answer
The 195 valid records are saved and committed. The 5 failures are rolled back. Loop over the returned List<Database.SaveResult>, check isSuccess() on each, and read getErrors() for the failed ones. Results are in the same order as the input list.