Sub topic 13
Practical Patterns: Guarded Blocks and Partial-Failure Handling
This chapter assumes you can write Apex classes and run DML. It also assumes you know try/catch with DmlException, and that you know what Database.setSavepoint and Database.rollback do. Here you combine them into two patterns you can reuse.
Pattern 1: The guarded block
A guarded block wraps related DML in a savepoint and a try/catch. If anything fails, the catch block rolls back to the savepoint. Without the rollback, a caught exception leaves earlier DML in place.
public with sharing class OnboardingService {
public static Id createAccountWithContact(String acctName, String lastName) {
Savepoint sp = Database.setSavepoint();
try {
Account acct = new Account(Name = acctName);
insert acct;
Contact c = new Contact(LastName = lastName, AccountId = acct.Id);
insert c;
return acct.Id;
} catch (DmlException e) {
Database.rollback(sp);
System.debug('Rolled back: ' + e.getMessage());
return null;
}
}
}Three habits keep this pattern safe:
- Set the savepoint before the first DML statement in the group, not after it.
- Roll back only for failures you have handled. If the caller should know about the failure, rethrow after the rollback.
- Do not reuse an
sObjectafter a rollback without clearing itsId. The row is gone from the database, but theIdstays on the in-memory record.
Savepoint sp = Database.setSavepoint();
Account a = new Account(Name = 'Temp');
insert a;
Database.rollback(sp);
a.Id = null; // clear the stale Id before inserting again
insert a;Pattern 2: Partial-failure handling
Sometimes you want valid records to save even when others fail. Use a Database method with allOrNone set to false. Each record gets its own SaveResult, and you decide what to do with the failures.
List<Account> accts = new List<Account>{
new Account(Name = 'Good'),
new Account() // missing required Name
};
Database.SaveResult[] results = Database.insert(accts, false);
List<String> failures = new List<String>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
failures.add('Row ' + i + ' ' + err.getStatusCode() + ': ' + err.getMessage());
}
}
}
System.debug(failures);Results come back in the same order as the input list, so the index tells you which record failed.
Choosing between the patterns
| Situation | Pattern |
|---|---|
| Parent and child records must exist together | Guarded block |
| A batch of independent records, some may be bad | Partial success |
| Several steps across different objects, all or nothing | Guarded block |
You can combine them. Use partial success for a list of independent records, and if too many fail, call Database.rollback(sp) to undo the successful ones as well.
Exercise
A method sets a savepoint, inserts an Account, then inserts a Contact that fails. The catch block logs the error but does not call Database.rollback. Is the Account saved when the transaction ends, and why?
Show answer
Yes. The exception was caught, so the transaction does not roll back automatically. The Account insert already succeeded, and only Database.rollback(sp) would undo it.
Exercise
You call Database.insert(records, false) with 200 records and 5 are invalid. How do you find out which ones failed?
Show answer
Loop over the returned SaveResult array. It has the same order as the input list. For each result where isSuccess() is false, call getErrors() and use the index to identify the record.