Sub topic 11
Reporting Errors per Record and Handling Partial Success
This chapter assumes you can read basic Apex and SOQL, and that you know a trigger receives a list of up to 200 records. Here you will see how to block individual bad records without failing the whole batch.
Why per-record errors matter
A trigger processes a batch. If you throw an exception, the whole transaction rolls back, and every record in the batch fails because of one bad row. The addError method avoids this. It marks one record, or one field on a record, as invalid and leaves the others alone.
trigger InvoiceLineTrigger on Invoice_Line__c (before insert, before update) {
for (Invoice_Line__c line : Trigger.new) {
if (line.Quantity__c != null && line.Quantity__c < 0) {
line.Quantity__c.addError('Quantity cannot be negative.');
}
}
}The call is on the field, so the message appears next to Quantity__c in the UI and in the API response for that record. You can also call line.addError('message') to attach the error to the record as a whole.
What happens next depends on the DML
addError only flags the record. What happens to the rest of the batch depends on how the DML was issued.
| Caller | Behavior when one record has an error |
|---|---|
| `insert records;` (all-or-none) | The whole statement fails and nothing is saved. |
| `Database.insert(records, false)` | Records without errors are saved. Failed records are reported in the results. |
| Data Loader or API with partial success | Valid rows save. Failed rows appear in the error file. |
You do not control the caller from inside the trigger. Write the trigger so it reports every bad record, and let the caller decide what to do with the rest.
Reading partial success results
When your own code uses Database.insert with allOrNone set to false, check each SaveResult. Skipping this check hides failures.
List<Invoice_Line__c> lines = new List<Invoice_Line__c>{
new Invoice_Line__c(Quantity__c = 5),
new Invoice_Line__c(Quantity__c = -1)
};
List<Database.SaveResult> results = Database.insert(lines, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug('Row ' + i + ' failed: ' + err.getMessage());
}
}
}Results come back in the same order as the input list, so the index identifies the failed record.
Common mistakes
- Throwing exceptions in the loop. An uncaught exception fails every record. Use
addErrorfor validation problems. - Calling
addErrorin an after trigger onTrigger.new. Records in after triggers are read-only, soaddErroron them raises an error. Validate in a before trigger. To block an after-trigger save, use the original record variable from a before context, or re-query is not needed if you validate earlier. - Ignoring results from
Database.insert. Withfalse, failures do not throw. You must inspect each result. - Using one message for many causes. Say which field and why, so the user can fix the data.
Exercise
A trigger on 200 records calls addError on 3 of them. The records are saved with Database.insert(records, false). How many records are saved, and how do you find the 3 that failed?
Show answer
197 records are saved. Loop over the returned List<Database.SaveResult>, which is in the same order as the input. For each result where isSuccess() is false, call getErrors() to read the messages, and use the index to identify the record.