Sub topic 7
Inspecting errors: status codes, messages, and fields
This chapter assumes you can write basic Apex, use try/catch, and call Database.insert with allOrNone set to false. Here you will learn to read the details of each failure.
Where error details live
When a Database method runs with allOrNone set to false, record-level errors do not throw an exception. Each result object (SaveResult, UpsertResult, DeleteResult) holds them instead. A failed result returns false from isSuccess(). Calling getErrors() on it returns a list of Database.Error objects.
A single record can have more than one error, so always loop over the list.
The three parts of Database.Error
Every Database.Error gives you three pieces of information.
| Method | Returns | Use it for |
|---|---|---|
| `getStatusCode()` | A `StatusCode` enum value | Deciding what to do in code |
| `getMessage()` | A human-readable string | Logs and user-facing text |
| `getFields()` | A list of field names | Pointing to the fields involved |
getStatusCode() is the one to branch on. Messages are text meant for people, and they can change. Comparing a status code to an enum value is safer than matching on message text.
Common status codes include:
REQUIRED_FIELD_MISSING: a required field has no value.STRING_TOO_LONG: a text value exceeds the field length.DUPLICATE_VALUE: a unique or external ID value already exists.FIELD_CUSTOM_VALIDATION_EXCEPTION: a validation rule or a custom error blocked the save.INSUFFICIENT_ACCESS_OR_READONLY: the user cannot edit or delete the record.
A worked example
The next example inserts one valid and one invalid account. It reads all three parts of each error.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account() // Name is required, so this record fails
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
Database.SaveResult sr = results[i];
if (!sr.isSuccess()) {
for (Database.Error err : sr.getErrors()) {
System.debug('Record ' + i + ' failed');
System.debug('Code: ' + err.getStatusCode());
System.debug('Message: ' + err.getMessage());
System.debug('Fields: ' + err.getFields());
}
}
}The second record fails with REQUIRED_FIELD_MISSING, and getFields() lists Name. The index i ties the error back to the input record at accounts[i], because results come back in the same order as the input.
Branching on the status code
Compare the status code with a StatusCode enum value. This lets you handle each kind of failure differently.
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()) {
continue;
}
for (Database.Error err : results[i].getErrors()) {
if (err.getStatusCode() == StatusCode.REQUIRED_FIELD_MISSING) {
System.debug('Record ' + i + ' needs: ' + err.getFields());
} else {
System.debug('Record ' + i + ' failed: ' + err.getMessage());
}
}
}Common mistakes
- Assuming
getFields()is never empty. Some errors apply to the whole record, such as a failing validation rule that is not tied to one field. In those cases the list can be empty. Check its size before you read the first item. - Reading only the first error. A record can fail for several reasons. Loop over
getErrors(). - Matching on message text. Messages can change. Use the status code.
- Losing the record. Result objects do not hold the input record. Use the list index to find it.
How errors differ from DML statements
A DML statement reports failure by throwing a DmlException. That exception has its own methods, such as getDmlStatusCode(index) and getDmlFieldNames(index), which return the same kinds of detail by record index. The Database methods hand you the details in result objects instead. The information is similar, but the access pattern differs.
Exercise
A record fails to save and getFields() returns an empty list. What does this tell you, and which value should your code branch on?
Show answer
The error applies to the whole record and not to one field, for example a validation rule that is not tied to a field. Your code should branch on getStatusCode(), not on the message text or the field list.
Exercise
You call Database.insert(records, false) and the third result has isSuccess() equal to false. How do you find the input record that failed?
Show answer
Use the same index. Results come back in the same order as the input list, so the failed record is records[2].