Sub topic 7
Inspecting errors: status codes, messages, and fields
This chapter covers how to read the errors that Database methods report when a record fails. It assumes you can write Apex classes and collections, use try/catch, and know that Database.insert(records, false) returns one result object per input record. The previous chapter showed how to read SaveResult, UpsertResult, and DeleteResult. Here you will look inside the errors those results carry.
Where errors live
Each result object has an isSuccess() method. When it returns false, call getErrors(). That method returns a List<Database.Error>. The list usually has one entry. It can have more than one, because a single record may break several rules at once.
A Database.Error exposes three methods you will use constantly.
| Method | Returns | What it tells you |
|---|---|---|
| `getStatusCode()` | `StatusCode` enum value | A machine-readable category, such as `REQUIRED_FIELD_MISSING` |
| `getMessage()` | `String` | A human-readable description, localized to the running user |
| `getFields()` | `List<String>` | API names of the fields involved in the error |
Status codes
getStatusCode() returns a value from the StatusCode enum. Compare it against enum values, not against message text. Messages can change between releases and differ by user language. Status codes are stable.
Some common values:
REQUIRED_FIELD_MISSING: a required field has no value.FIELD_CUSTOM_VALIDATION_EXCEPTION: a validation rule rejected the record.DUPLICATE_VALUE: a unique field or external ID collides with an existing value.STRING_TOO_LONG: a text value exceeds the field length.INVALID_CROSS_REFERENCE_KEY: a lookup points to a record that does not exist or is not visible.ENTITY_IS_DELETED: the record was already deleted.INSUFFICIENT_ACCESS_OR_READONLY: the user lacks permission to save the record.UNABLE_TO_LOCK_ROW: another transaction holds a lock on the record.
A switch statement on the enum keeps the handling readable. The next example runs a single failing insert and branches on the code.
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++) {
if (results[i].isSuccess()) {
continue;
}
for (Database.Error err : results[i].getErrors()) {
switch on err.getStatusCode() {
when REQUIRED_FIELD_MISSING {
System.debug('Record ' + i + ' is missing: ' + err.getFields());
}
when FIELD_CUSTOM_VALIDATION_EXCEPTION {
System.debug('Record ' + i + ' broke a validation rule: ' + err.getMessage());
}
when else {
System.debug('Record ' + i + ' failed with ' + err.getStatusCode());
}
}
}
}The when values are written as bare enum names. Apex accepts that form in a switch on an enum.
Messages
getMessage() gives text you can show to a user or write to a log. For a validation rule, it returns the error message the admin configured on the rule. For system errors, it returns Salesforce's standard wording.
Use messages for display and logging. Do not parse them to decide what to do. If you need to branch, use the status code.
Fields
getFields() returns a list of field API names. Treat it as a hint, not a guarantee.
- For
REQUIRED_FIELD_MISSING, the list normally names the missing field. - For a validation rule that is attached to a specific field, the list names that field. If the rule shows its error at the top of the page instead, the list is empty.
- For errors about the record as a whole, such as
UNABLE_TO_LOCK_ROWorINSUFFICIENT_ACCESS_OR_READONLY, the list is usually empty.
Always handle an empty list. Calling getFields()[0] without a size check throws a ListException and hides the original problem.
String describeFields(Database.Error err) {
List<String> fields = err.getFields();
return fields.isEmpty() ? '(no specific field)' : String.join(fields, ', ');
}Errors from DML statements
A DML statement does not give you result objects. When it fails, it throws a DmlException. That exception exposes the same three pieces of information, but through different methods, indexed by the position of the failed record.
| Database.Error method | DmlException equivalent |
|---|---|
| `getStatusCode()` | `getDmlType(index)` |
| `getMessage()` | `getDmlMessage(index)` |
| `getFields()` | `getDmlFieldNames(index)` |
getNumDml() returns how many records failed, and getDmlIndex(i) returns the position in the input list of the i-th failure. That is the number to pass to the other methods.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme'),
new Account()
};
try {
insert accounts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug('Input row ' + e.getDmlIndex(i)
+ ' failed: ' + e.getDmlType(i)
+ ' - ' + e.getDmlMessage(i)
+ ' ' + e.getDmlFieldNames(i));
}
}The loop variable i counts failures. The value returned by getDmlIndex(i) is the index in the original list. Mixing the two up is a common mistake.
Reporting errors back to records
An error is more useful when it is tied to the record that caused it. Two techniques apply.
First, you can attach the message to the record with addError. This works in triggers and in code that runs before the user sees the record, and it shows the message in the interface. Second, you can collect failures in your own structure for logging or return values.
The helper below builds a map from the input index to a list of readable error strings. It works for any List<Database.SaveResult>.
public class DmlErrorReport {
public static Map<Integer, List<String>> collect(List<Database.SaveResult> results) {
Map<Integer, List<String>> failures = new Map<Integer, List<String>>();
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
continue;
}
List<String> lines = new List<String>();
for (Database.Error err : results[i].getErrors()) {
lines.add(err.getStatusCode() + ': ' + err.getMessage()
+ (err.getFields().isEmpty() ? '' : ' [' + String.join(err.getFields(), ', ') + ']'));
}
failures.put(i, lines);
}
return failures;
}
}Because results come back in the same order as the input, failures.get(3) describes accounts[3]. You can then log it, return it from an @AuraEnabled method, or write it to a custom object.
Common errors when reading errors
- Checking messages instead of codes. A comparison like
err.getMessage().contains('required')breaks when the text or the user's language changes. - Assuming one error per record. Loop over
getErrors(). Reading only the first entry hides other problems. - Assuming
getFields()is populated. It can be empty. Check before indexing. - Ignoring
isSuccess(). On a successful result,getErrors()returns an empty list or no useful data. Check success first and keep your failure logic in one branch. - Calling
getId()on a failed insert. The ID isnullwhen the save failed. Use the input index to identify the record. - Swallowing failures in partial-success mode. With
allOrNoneset tofalse, no exception is thrown. If you do not inspect the results, failed records disappear without any sign.
Putting it together
The scenario below inserts contacts, some of which refer to a nonexistent account. It reports each failure by input position, code, and fields.
List<Contact> contacts = new List<Contact>{
new Contact(LastName = 'Smith'),
new Contact(LastName = 'Jones', AccountId = '001000000000000AAA'),
new Contact(FirstName = 'No Last Name')
};
List<Database.SaveResult> results = Database.insert(contacts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
Database.Error first = results[i].getErrors()[0];
System.debug('Row ' + i + ' => ' + first.getStatusCode()
+ ' | ' + first.getMessage()
+ ' | ' + first.getFields());
}
}The second row fails with a cross-reference error because the account ID does not exist. The third row fails because LastName is required. The first row saves.
Exercise
A Database.insert call with allOrNone set to false returns 200 results. Result 41 has isSuccess() equal to false, and its single Database.Error has an empty getFields() list. Name two reasons that could be true, and say which method you would use to decide how your code reacts.
Show answer
The error may apply to the record as a whole rather than to one field (for example UNABLETOLOCKROW or INSUFFICIENTACCESSORREADONLY), or it may come from a validation rule that shows its message at the top of the page rather than on a field. Use getStatusCode() to decide how to react, because status codes are stable enum values. Use getMessage() only for display or logging, and check getFields().isEmpty() before reading from the list.
Exercise
A DmlException from insert accounts; reports getNumDml() equal to 2. The first failure has getDmlIndex(0) equal to 3, and the second has getDmlIndex(1) equal to 7. Which positions in the accounts list failed, and which index do you pass to getDmlMessage to read the second failure's message?
Show answer
Positions 3 and 7 in the accounts list failed. Pass 1 to getDmlMessage, because that method takes the failure number, not the input position. Use getDmlIndex(1), which returns 7, to find the matching record in the list.