Sub topic 11
Reporting Errors Per Record and Handling Partial Success
This chapter assumes you can write basic triggers, know the difference between Trigger.new and Trigger.oldMap, and have used insert, update, and Database.insert. You will learn how to reject single records inside a batch, how the DML option allOrNone decides what happens to the rest of the batch, and how to report failures from DML you run inside a trigger.
Why one bad record should not throw an exception
A trigger receives up to 200 records. If record 37 breaks a business rule, the simplest reaction is throw new MyException(...). That aborts the whole transaction and discards the other 199 records, even when the caller asked for partial success.
addError is the alternative. It attaches an error message to one record, or to one field of one record, and lets the loop continue. Salesforce then decides what to do with the marked records based on how the original DML statement was called.
Record-level and field-level errors
There are two forms of addError:
record.addError('message')marks the whole record. The message appears at the top of the page in the UI.record.Field__c.addError('message')marks one field. In the UI the message appears next to that field. In the API it is returned with the field name.
The field-level form is used in this trigger:
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.');
}
if (line.Quantity__c == null && line.Unit_Price__c != null) {
line.addError('Enter a quantity when a unit price is set.');
}
}
}Both calls run inside a normal loop. There is no SOQL or DML here, so the trigger is bulk safe. The loop never stops early, so every bad record in the batch is flagged in one pass.
You can call addError in before and after triggers. In an after trigger you cannot change field values on Trigger.new, but you can still mark records with errors. Marking a record in an after trigger rolls back that record's save, including work the trigger already did for it, such as related records inserted earlier in the same transaction.
What happens to the rest of the batch
The result depends on the allOrNone setting of the DML that fired the trigger.
| Caller | `allOrNone` | Effect of `addError` on one record |
|---|---|---|
| `insert list;` or `update list;` | true | Whole statement fails with a `DmlException`. No record is saved. |
| `Database.insert(list, true)` | true | Same as above. |
| `Database.insert(list, false)` | false | Only flagged records fail. Others save. Errors are returned in the results. |
| Bulk API, Data Loader | usually false | Flagged rows are reported as failed. Other rows save. |
| UI save of one record | not applicable | The user sees the message and the record is not saved. |
Your trigger code is identical in every row. The caller chooses the behavior, which is why the trigger should only flag records and should not guess about the rest of the batch.
Reading partial-success results
When you call DML from Apex with allOrNone set to false, nothing is thrown for row-level failures. You must read the results yourself.
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 + ': ' + err.getStatusCode()
+ ' ' + err.getMessage() + ' ' + err.getFields());
}
}
}The results list has the same order and size as the input list. That ordering is what lets you map a failure back to the record that caused it. Database.update returns SaveResult too, Database.upsert returns UpsertResult, and Database.delete returns DeleteResult. All three have isSuccess() and getErrors().
If you skip the loop, failures are silently lost. This is the main risk of partial success.
Reporting failures from DML inside a trigger
A trigger often writes related records. A plain insert tasks; throws one DmlException if any task fails, which takes down every opportunity in the batch. To fail only the opportunity whose task could not be created, use partial success and copy each failure back onto the source record with addError.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
List<Opportunity> newlyWon = new List<Opportunity>();
for (Opportunity opp : Trigger.new) {
Boolean wasWon = Trigger.oldMap != null
&& Trigger.oldMap.get(opp.Id).StageName == 'Closed Won';
if (opp.StageName == 'Closed Won' && !wasWon) {
newlyWon.add(opp);
}
}
if (!newlyWon.isEmpty()) {
OpportunityTaskService.createFollowUpTasks(newlyWon);
}
}
public with sharing class OpportunityTaskService {
public static void createFollowUpTasks(List<Opportunity> wonOpps) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : wonOpps) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
List<Database.SaveResult> results = Database.insert(tasks, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
String reason = results[i].getErrors()[0].getMessage();
wonOpps[i].addError('Follow-up task could not be created: ' + reason);
}
}
}
}Three details make this work:
tasksandwonOppsare built in the same loop, so indexirefers to the same opportunity in both lists.- The records in
wonOppsare the same objects that came fromTrigger.new.addErroronly has an effect on records of the current trigger context. Calling it on a copy or on a freshly queried record does nothing for the save. - There is one DML statement for the whole batch. The error handling adds a loop over results but no extra statements.
If you build the task list conditionally and skip some opportunities, the indexes no longer match. In that case store the source record in a parallel list or in a Map<Integer, Opportunity> while you build the tasks.
Gotchas
- Salesforce can invoke a trigger more than once when some records in a partial-success batch fail. The first pass runs with the full batch, the flagged records are removed, and the remaining records are processed again. The second invocation can run in the same transaction. Do not assume one invocation per DML statement.
- A static "already processed" set, as covered in the recursion chapter, can interact badly with that retry. Records marked as processed in the first pass may be skipped in the second. Test partial-success inserts when you use a static guard.
addErrordoes not stop your own code. Statements after it still run, so avoid doing work on a record you have just rejected.- Error messages are HTML-escaped by default. Do not put user-supplied text in a message and then switch off escaping.
Testing both modes
Test the all-or-none path and the partial-success path separately, and use 200 records so a batch contains both good and bad rows. The test below assumes Invoice_Line__c has no other required fields.
@IsTest
private class InvoiceLineTriggerTest {
private static List<Invoice_Line__c> buildLines() {
List<Invoice_Line__c> lines = new List<Invoice_Line__c>();
for (Integer i = 0; i < 200; i++) {
// Every tenth line gets a negative quantity (20 bad rows).
lines.add(new Invoice_Line__c(Quantity__c = Math.mod(i, 10) == 0 ? -1 : 1));
}
return lines;
}
@IsTest
static void partialSuccessSavesValidRows() {
List<Database.SaveResult> results = Database.insert(buildLines(), false);
Integer failures = 0;
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failures++;
}
}
System.assertEquals(20, failures, 'Negative quantities should be rejected');
System.assertEquals(180, [SELECT COUNT() FROM Invoice_Line__c]);
}
@IsTest
static void allOrNoneSavesNothing() {
Boolean threw = false;
try {
insert buildLines();
} catch (DmlException e) {
threw = true;
System.assert(e.getMessage().contains('Quantity cannot be negative'));
}
System.assert(threw, 'Expected a DmlException');
System.assertEquals(0, [SELECT COUNT() FROM Invoice_Line__c]);
}
}Summary of rules
- Use
addErrorto reject a record. Do not throw an exception from inside a loop overTrigger.new. - Prefer the field-level form when the problem belongs to one field.
- Let the caller decide
allOrNone. Your trigger only flags records. - When your trigger runs DML, use
Databasemethods withallOrNoneset to false, read every result, and calladdErroron the matching source record. - Test with a mixed batch in both modes.
Exercise
A trigger on Contact (after insert) creates one Case per contact with Database.insert(cases, false). A user loads 200 contacts with the Bulk API, and 5 of the cases fail validation. The trigger does not read the SaveResult list. What does the user see, and how do you fix it?
Show answer
The 5 contacts save without their cases, and nothing reports the problem, because partial-success DML does not throw for row-level failures. To fix it, build the Case list and a parallel list of source contacts in the same loop. After the insert, loop over the SaveResult list by index. For each result where isSuccess() is false, call addError with the message from getErrors()[0].getMessage() on the matching contact from Trigger.new. Because the load uses partial success, only those 5 contacts fail, and the Bulk API reports them as errors.