Sub topic 2
allOrNone: all-or-nothing versus partial success
Assume you know basic Apex collections, SObjects, try/catch, and Salesforce transactions. This chapter focuses on how Apex reports DML errors when saving several records.
Choosing all-or-none behavior
A DML statement such as insert records is all-or-nothing. If one record fails, Apex throws a DmlException, and the operation rolls back.
The Database class lets you choose. Pass false for allOrNone to keep valid records and report failures for the others.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Saved record ' + results[i].getId());
} else {
System.debug('Input record ' + i + ' failed');
}
}Here, the first account can be saved even though the second account has no required Name.
Reading result objects
Database methods return one result object for each input record, in the same order. The object type depends on the operation.
| Operation | Result type | Useful information |
|---|---|---|
| `insert` or `update` | `SaveResult` | Success, record ID, errors |
| `upsert` | `UpsertResult` | Success, ID, errors, created or updated |
| `delete` or `undelete` | `DeleteResult` | Success, errors |
For an upsert, isCreated() distinguishes an inserted record from an updated record. Always inspect isSuccess() before reading an ID.
Inspecting errors
A failed result can contain several Database.Error objects. Each error provides a status code, a readable message, and fields related to the failure.
for (Database.SaveResult result : results) {
if (!result.isSuccess()) {
for (Database.Error error : result.getErrors()) {
System.debug(error.getStatusCode());
System.debug(error.getMessage());
System.debug(error.getFields());
}
}
}Matching results to input records
Because result order matches input order, use the list index to identify the original record. This is safer than matching by name, which might not be unique.
Governor limits and bulkification
Both DML statements and Database methods count against the same DML governor limits. Changing the syntax does not create extra capacity. Collect records first, then perform one operation outside loops.
Exercise
Which approach should you use when valid records must be saved even if some records fail?
Show answer
Use a Database method with allOrNone set to false and inspect each returned result.