Sub topic 8
Partial success in practice: matching results to input records
This chapter assumes you know basic Apex, how try/catch works, and that Database.insert(records, false) returns a list of result objects. Here you will use those results to decide what to do about each failed record.
Why matching matters
With allOrNone set to false, the valid records are saved and the failed ones are reported. The result list is in the same order as the input list. results[i] always describes records[i].
A SaveResult for a failed record does not include the record. For an insert, it has no ID either. The index is the only link back to your data.
Pairing by index
Loop with an integer index so you can reach both the result and its input record.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account(), // Name is required, so this record fails
new Account(Name = 'Globex')
};
List<Database.SaveResult> results = Database.insert(accounts, false);
List<Account> saved = new List<Account>();
List<Account> failed = new List<Account>();
Map<Integer, String> failureReasons = new Map<Integer, String>();
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
saved.add(accounts[i]);
} else {
failed.add(accounts[i]);
List<String> messages = new List<String>();
for (Database.Error err : results[i].getErrors()) {
messages.add(err.getStatusCode() + ': ' + err.getMessage());
}
failureReasons.put(i, String.join(messages, '; '));
}
}
System.debug('Saved: ' + saved.size());
System.debug('Failed: ' + failed.size());
System.debug(failureReasons);After a successful insert, Apex also sets the Id on each saved record in your input list. You can use saved directly in later steps, such as inserting child records.
What to do with failures
Once you have separated the two groups, pick a response that fits your requirement:
- Log the failures to a custom object so someone can review them.
- Retry only the failed records after fixing the cause.
- Report the errors to the user or caller.
- Skip the failed records and continue, if they are not critical.
A single record can have more than one error, so always loop over getErrors() rather than reading only the first.
Matching by key instead of index
The index works when the list you passed in is the list you inspect. If you build a different list later, such as a filtered copy, the positions no longer line up. In that case, record the link while you still have it. For an update, the record Id is a stable key:
List<Account> toUpdate = [SELECT Id, Name FROM Account LIMIT 10];
for (Account a : toUpdate) {
a.Name = a.Name + ' Updated';
}
List<Database.SaveResult> results = Database.update(toUpdate, false);
Set<Id> failedIds = new Set<Id>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failedIds.add(toUpdate[i].Id);
}
}
System.debug('Failed IDs: ' + failedIds);Inserts have no ID before saving, so use the index, or an external ID field if the object has one.
Common mistakes
- Assuming
getId()works for failures. On a failed insert it returnsnull. - Sorting or modifying the input list between the call and the loop. This breaks the index pairing.
- Ignoring the results. With
allOrNoneset tofalse, no exception is thrown for record-level errors. If you discard the return value, failures pass silently.
Exercise
You call Database.insert(contacts, false) with 5 contacts. results[2].isSuccess() is false. Which input record failed, and why can't you read its ID from the result?
Show answer
The failed record is contacts[2], because results keep the input order. getId() returns null for a failed insert, since no record was created and so no ID exists.