Sub topic 8
Partial success in practice: matching results to input records
This chapter assumes you can write basic Apex classes and methods and work with Lists and Maps of SObjects. It also assumes you know try/catch, and you have seen Database.insert(records, false) and the result objects in earlier chapters. Here you will use them to answer one question: after a partial-success call, which input record failed, and why?
Why matching matters
With allOrNone set to false, the call does not throw when individual records fail. It returns a result object for every record, and your code has to read them. If you skip that step, failures pass silently. The user sees a success screen while some rows were never saved.
The result list lines up with the input list:
- The result list has the same size as the input list.
- Result
idescribes input recordi. - This holds for
Database.insert,update,upsert,delete, andundelete.
That ordering is the only reliable link between a failure and the record that caused it. Successful records also have their Id set on the original SObject after an insert. Failed records keep a null Id.
The core pattern: loop by index
Use an indexed for loop, not a for-each loop. A for-each loop over the results loses the position, and the position is the link to the input.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Rivera', Email = '[email protected]'),
new Contact(Email = '[email protected]'),
new Contact(LastName = 'Okafor', Email = '[email protected]')
};
List<Database.SaveResult> results = Database.insert(contacts, false);
for (Integer i = 0; i < results.size(); i++) {
Contact original = contacts[i];
Database.SaveResult sr = results[i];
if (sr.isSuccess()) {
System.debug('Saved ' + original.LastName + ' as ' + sr.getId());
} else {
for (Database.Error err : sr.getErrors()) {
System.debug('Row ' + i + ' (' + original.Email + ') failed: '
+ err.getStatusCode() + ' - ' + err.getMessage()
+ ' fields=' + err.getFields());
}
}
}The second contact has no LastName, so it fails with a required-field error. The first and third are saved. Row 1 is the failure, and contacts[1] gives you the record you can show to the user.
A single record can carry several errors, which is why the inner loop calls getErrors() and iterates. Do not assume the list has one entry.
Choosing a matching key
The index always works. For some operations you can also match by Id.
| Operation | Result type | Match by index | Match by Id |
|---|---|---|---|
| insert | `SaveResult` | Yes | Only for successes. Failed rows have a null `Id`. |
| update | `SaveResult` | Yes | Yes. Compare with the input `Id`. |
| upsert | `UpsertResult` | Yes | Only for successes. |
| delete | `DeleteResult` | Yes | Yes, when you passed IDs or records with IDs. |
| undelete | `UndeleteResult` | Yes | Yes. |
After an insert, a failed row has no Id, so a Map<Id, String> cannot hold it. Use the index as the key.
Packaging the results for callers
A helper that returns structured errors keeps the loop in one place. The following class is complete and can be saved as it is.
public with sharing class SaveOutcome {
public class RowError {
public Integer index;
public String statusCode;
public String message;
public List<String> fields;
}
public List<RowError> errors = new List<RowError>();
public Integer successCount = 0;
public static SaveOutcome insertRecords(List<SObject> records) {
SaveOutcome outcome = new SaveOutcome();
List<Database.SaveResult> results = Database.insert(records, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
outcome.successCount++;
continue;
}
for (Database.Error err : results[i].getErrors()) {
RowError re = new RowError();
re.index = i;
re.statusCode = String.valueOf(err.getStatusCode());
re.message = err.getMessage();
re.fields = err.getFields();
outcome.errors.add(re);
}
}
return outcome;
}
}A caller can now report outcome.errors to a user, write them to a log object, or decide whether to retry. Because each RowError carries the index, the caller can look up the original record in the list it passed in. This holds as long as the caller does not reorder or modify the list in between.
Collecting the failed records for a retry
Often you want the failed records as a list, so you can fix them and try again, or send them somewhere else. Use a Set<Integer> of failed indexes first, then build the list. This avoids adding the same record twice when it has several errors.
public static List<Contact> failedContacts(
List<Contact> input,
List<Database.SaveResult> results
) {
Set<Integer> failedIndexes = new Set<Integer>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failedIndexes.add(i);
}
}
List<Contact> failed = new List<Contact>();
for (Integer i = 0; i < input.size(); i++) {
if (failedIndexes.contains(i)) {
failed.add(input[i]);
}
}
return failed;
}Do not re-run the whole list. Records that already saved would be inserted again as duplicates. Keep the successes out of the retry list.
Matching by Id for updates and deletes
For updates and deletes, the records already have IDs, so a map from Id to message is convenient.
List<Contact> toUpdate = [SELECT Id, Email FROM Contact LIMIT 50];
for (Contact c : toUpdate) {
c.Email = 'not-an-email';
}
List<Database.SaveResult> results = Database.update(toUpdate, false);
Map<Id, String> errorsById = new Map<Id, String>();
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
errorsById.put(toUpdate[i].Id, results[i].getErrors()[0].getMessage());
}
}
System.debug(errorsById);Notice that the key comes from toUpdate[i].Id, the input record. It does not come from the result. Taking the Id from the input is the safest choice, because it works whether or not the result object carries one.
Deletes follow the same shape. Database.delete accepts a list of IDs or records and returns one DeleteResult per entry, in order.
List<Id> idsToDelete = new List<Id>();
for (Contact c : [SELECT Id FROM Contact WHERE Email = 'not-an-email' LIMIT 20]) {
idsToDelete.add(c.Id);
}
List<Database.DeleteResult> deleteResults = Database.delete(idsToDelete, false);
for (Integer i = 0; i < deleteResults.size(); i++) {
if (!deleteResults[i].isSuccess()) {
System.debug('Could not delete ' + idsToDelete[i] + ': '
+ deleteResults[i].getErrors()[0].getMessage());
}
}Edge cases and gotchas
Not every problem becomes a result object
allOrNone = false covers record-level failures such as validation rules, required fields, and trigger errors added with addError. Other problems still stop the call:
- Governor limit violations raise a
LimitException, which you cannot catch. A partial-success call still counts as one DML statement and consumes DML rows for every record you pass in, whether it saves or not. - A null list argument raises an exception instead of returning results.
If you need protection from the exceptions that can still occur, keep a try/catch around the call even when you inspect results.
Dependent records in the same list
If a record in the list depends on another record in the same call, a failure in one can cause a failure in the other. The dependent record's error message usually points at the failed parent, for example a status code about a missing or invalid parent reference. Read the status code and do not assume that each failure has an independent cause.
Triggers can run more than once
When some records in a batch fail and others succeed, the platform can re-run the successful records so that they save without the failed ones. Your triggers and flows can therefore fire more than once for the same record in one call. Do not use a static variable as a "has run" flag without thinking about this. Write trigger logic so that running twice does no harm.
Do not rely on `getFields()` alone
getFields() can return an empty list. Errors that are not tied to a single field, such as a failed validation rule that applies to the whole record, do not name a field. Always log the status code and message too.
Report in a way users can act on
Showing "3 records failed" is rarely enough. Include the index or a business key such as an email address or external ID. Include the message too. In a batch job, write failures to a custom log object so you can find them later.
Putting it together
A solid partial-success routine does five things:
- Calls the
Databasemethod withfalseforallOrNone. - Loops over the results by index.
- Reads every error of every failed result, using the status code, message, and fields.
- Pairs each failure with the original record, by index or by input
Id. - Acts on the failures by reporting, logging, or retrying only the failed rows.
If your code skips steps 2 to 5, a statement with a try/catch is probably the better tool. It fails loudly instead of silently.
Exercise
You call Database.insert(accounts, false) with 5 accounts, and the result list shows failures at indexes 1 and 3. A teammate suggests re-running Database.insert(accounts, false) on the whole list after fixing the data. Why is that a bad idea, and what should you do instead?
Show answer
Accounts at indexes 0, 2, and 4 were already saved, so inserting the whole list again creates duplicate accounts. Collect only the failed records (accounts[1] and accounts[3]) using the indexes of the failed results, fix them, and insert just those. Alternatively, use an upsert with an external ID so a re-run does not create duplicates.
Exercise
Why can you not use a Map<Id, String> keyed by the result's Id to record the errors from a partial-success insert?
Show answer
A failed insert has no record Id, so getId() is null for failed rows and the map keys would be null or would collide. Use the index as the key, because the result list has the same order as the input list.