Sub topic 13
Practical patterns: guarded blocks and partial-failure handling
This chapter assumes you know basic Apex syntax, how to run DML (insert, update) on sObjects, and how try/catch and DmlException work. It also assumes you know that Apex has governor limits. It builds on the earlier chapters about savepoints, Database.rollback, and what a rollback does not revert.
The two patterns here answer two different questions:
- Guarded block: several related changes must succeed together or not at all, and your code should keep running after a failure.
- Partial-failure handling: many independent records are being saved, and one bad record should not block the rest.
Choosing a pattern
| Situation | Pattern | Main tool |
|---|---|---|
| Parent and child records must exist together | Guarded block | `Database.setSavepoint`, `Database.rollback` |
| A batch of unrelated records, where good ones should save | Partial failure | `Database.insert(records, false)` |
| A batch where too many failures make the whole run invalid | Both combined | Savepoint plus `allOrNone = false` and a threshold |
| Any failure should stop everything and the caller does not catch it | Neither | Let the exception propagate |
The last row matters. An unhandled exception already rolls back the whole transaction. Add a savepoint only when your code catches the error and continues.
Pattern 1: the guarded block
A guarded block has four parts. It sets a savepoint, does the related DML inside try, rolls back in catch, and then reports the failure to the caller.
public with sharing class AccountContactService {
public class ServiceException extends Exception {}
public static Id createAccountWithContact(String accountName, String lastName) {
Savepoint sp = Database.setSavepoint();
try {
Account acct = new Account(Name = accountName);
insert acct;
insert new Contact(LastName = lastName, AccountId = acct.Id);
return acct.Id;
} catch (DmlException e) {
Database.rollback(sp);
throw new ServiceException('Could not create account and contact: ' + e.getMessage());
}
}
}If the contact insert fails, the account insert has already been executed. Catching the DmlException alone would leave that account in the transaction, and it would be committed when the transaction ends. Database.rollback(sp) removes it.
The callout below covers the decision this pattern forces on you.
Choosing what to catch
The example catches only DmlException. A NullPointerException or QueryException inside the block would skip the rollback and propagate. That is acceptable if nothing upstream catches it, because the transaction rolls back automatically. If a caller might catch it, use catch (Exception e) so the rollback always runs.
Keep the block small
Every setSavepoint and every rollback counts as a DML statement against the limit of 150 per transaction. Keep the guarded block around the smallest group of related DML, and bulkify the work inside it.
// Avoid: two extra DML statements for every record
for (Account a : accounts) {
Savepoint sp = Database.setSavepoint();
// ...per-record DML...
}With 200 records, that loop spends 200 DML statements on savepoints before any real work. If you roll back in some iterations, it spends more. Set one savepoint around the bulk operation instead. If you need per-record isolation, use partial success, described next.
Pattern 2: partial-failure handling
Database.insert(records, false) sets allOrNone to false. Valid records are saved, and each failure is reported in the matching Database.SaveResult instead of failing the statement.
The results array is in the same order as the input list. Use an index loop to pair each result with its record.
public with sharing class AccountLoader {
public static List<String> insertAccounts(List<Account> accts) {
List<String> failures = new List<String>();
Database.SaveResult[] results = Database.insert(accts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
List<String> messages = new List<String>();
for (Database.Error err : results[i].getErrors()) {
messages.add(err.getStatusCode() + ': ' + err.getMessage());
}
failures.add('Row ' + i + ' (' + accts[i].Name + '): ' + String.join(messages, '; '));
}
}
return failures;
}
}Keep in mind how this pattern behaves:
- No exception is thrown for a record-level failure. If you never read the results, failures are invisible.
- The records that succeeded are not rolled back. They stay in the transaction and are committed at the end unless something else fails.
- A trigger that calls
addErroron one record fails only that record underallOrNone = false. Under the default all-or-none behavior, the sameaddErrorfails the whole statement. - Some errors still throw, even with
allOrNone = false. An example is a limit exception, which cannot be caught at all.
Reporting the failures
Return the failure list, log it, or write it to a custom object. Be careful with the last option. If the transaction later rolls back, those log records roll back too. Logs that must survive a rollback need to be written in a separate transaction, such as a queueable job or a platform event.
Combining the patterns: a failure threshold
Sometimes partial success is fine up to a point. For example, a load can tolerate a few bad rows but should be abandoned if many fail. Combine the two patterns: save with allOrNone = false, count failures, and roll back to a savepoint if the count is too high.
public with sharing class ThresholdLoader {
public class LoadException extends Exception {}
public static Integer insertWithThreshold(List<Account> accts, Integer maxFailures) {
Savepoint sp = Database.setSavepoint();
Database.SaveResult[] results = Database.insert(accts, false);
Integer failures = 0;
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failures++;
}
}
if (failures > maxFailures) {
Database.rollback(sp);
for (Account a : accts) {
a.Id = null; // rollback does not clear Ids on in-memory records
}
throw new LoadException(failures + ' of ' + accts.size() + ' records failed.');
}
return accts.size() - failures;
}
}The loop that sets a.Id = null matters if the caller might retry with the same list. The rollback removed the database rows, but the successfully inserted records still hold their old Id values in memory. Inserting such a record again fails.
The same rollback does not reset static variables, so counters or caches kept in static fields still show the values from before the rollback. Reset them yourself if later code depends on them.
Common mistakes
- Rolling back inside a loop. Each rollback costs a DML statement, and a rollback also invalidates any savepoint set after the one you rolled back to. Roll back once, to the earliest savepoint you need.
- Rolling back to a stale savepoint. After
Database.rollback(sp1), a later savepointsp2is invalid, and using it throws a runtime error. - Ignoring
SaveResult. WithallOrNone = false, nothing tells you about failures unless you inspect the results. - Doing a callout after DML. A callout made while DML is uncommitted in the same transaction raises the uncommitted work pending error. A savepoint does not change that. Make callouts before the DML, or move them to asynchronous Apex.
- Expecting a rollback to undo everything. Emails already queued for sending, static variables, and
Idfields on in-memory records are not reverted.
Verifying the guarded block
A test for the guarded block triggers a failure on the second DML statement and checks that the first was undone.
@IsTest
private class AccountContactServiceTest {
@IsTest
static void rollsBackAccountWhenContactFails() {
Integer before = [SELECT COUNT() FROM Account];
try {
// A null LastName makes the Contact insert fail after the Account insert succeeds
AccountContactService.createAccountWithContact('Acme Test', null);
System.assert(false, 'Expected a ServiceException');
} catch (AccountContactService.ServiceException e) {
System.assert(e.getMessage().contains('Could not create'));
}
System.assertEquals(before, [SELECT COUNT() FROM Account]);
}
}The final assertion proves the rollback ran. If you removed Database.rollback(sp) from the service, the exception would still be caught and the count would be one higher, so the test would fail.
Exercise
A method calls Database.insert(accts, false) on 100 accounts, and 10 fail. The method then calls Database.rollback(sp) using a savepoint set before the insert, and finally inserts the same list again. What happens, and what must you do first?
Show answer
The rollback removes the 90 accounts that saved, but those 90 records still have their old Id values in memory. Inserting the list again would fail for them. Set Id to null on each record before the second insert. The 10 failed records have no Id, so they need no change. The savepoint and rollback also each cost one DML statement.
Exercise
A developer wraps each iteration of a 200-record loop in its own savepoint, try/catch, and rollback to isolate bad records. Why is this a problem, and what is a better design?
Show answer
Each setSavepoint call counts as a DML statement, and so does each rollback. 200 iterations use at least 200 statements of the 150-statement limit, so the transaction fails with a limit exception. Use Database.insert(records, false) and inspect the SaveResult array, so one DML statement handles all records and each failure is reported individually.