Sub topic 9
Handling DML failures with DmlException
A DML statement can fail for many reasons: a missing required field, a failed validation rule, a trigger that calls addError, a record locked by another transaction. In all of these cases Apex throws a DmlException. This chapter covers how to catch it, how to find out which records failed and why, and what state your data is in afterward.
This chapter assumes you know the basics of try, catch, and finally, the common built-in exception types, and the generic exception methods such as getMessage. It also assumes you are comfortable with insert, update, and delete statements.
When Apex throws a DmlException
A DML statement (insert, update, upsert, delete, undelete, merge) uses all-or-none behavior by default. If any record in the list fails, the whole statement fails, and Apex throws one DmlException that describes every failure.
Common causes include:
- A required field is empty.
- A validation rule rejects the record.
- A trigger calls
addErroron a record or field. - A unique or duplicate rule is violated.
- A lookup points to a record that does not exist or is not visible.
- Another transaction holds a lock on the row (
UNABLE_TO_LOCK_ROW). - Setup and non-setup objects are mixed in one transaction (
MIXED_DML_OPERATION).
Governor limit violations are different. Exceeding the DML statement or DML row limit throws a LimitException, which you cannot catch. A later chapter covers it.
Reading the details of each failure
getMessage() on a DmlException returns a summary, and it is often just the first failure. For per-record detail, use the DML-specific methods. Each takes the index of a failure, from 0 to getNumDml() - 1.
| Method | Returns |
|---|---|
| `getNumDml()` | Number of failed records |
| `getDmlIndex(i)` | Position of the failed record in the original list |
| `getDmlMessage(i)` | Error message for failure `i` |
| `getDmlFieldNames(i)` | `List<String>` of field names involved |
| `getDmlFields(i)` | `List<Schema.SObjectField>` of the same fields |
| `getDmlStatusCode(i)` | Status code as a string, such as `REQUIRED_FIELD_MISSING` |
| `getDmlType(i)` | Status code as a `System.StatusCode` enum value |
| `getDmlId(i)` | Id of the failed record, or `null` for inserts |
The loop variable i indexes the list of failures, not the list of records you submitted. To find the original record, use getDmlIndex(i).
try {
insert new Account();
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug(e.getDmlFieldNames(i) + ': ' + e.getDmlMessage(i));
}
}The output for this example looks like (Name): Required fields are missing: [Name]. The field list can be empty. Validation rules and trigger errors that are not tied to a field report an empty list.
Mapping failures back to records
The following example inserts three accounts, one of which has no name. It uses getDmlIndex to report which submitted record failed.
List<Account> accts = new List<Account>{
new Account(Name = 'Alpha'),
new Account(),
new Account(Name = 'Gamma')
};
try {
insert accts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
Integer position = e.getDmlIndex(i);
System.debug('Record at index ' + position + ' failed: '
+ e.getDmlStatusCode(i) + ' - ' + e.getDmlMessage(i));
}
}
System.debug('Saved: ' + [SELECT COUNT() FROM Account WHERE Name IN ('Alpha', 'Gamma')]);The last line prints Saved: 0 in an org with no accounts of those names. Because the statement is all-or-none, the valid records Alpha and Gamma were not saved either. If you want the valid records to save, use partial success, which a later chapter covers.
Branching on the status code
Different failures need different responses. Switch on the status enum from getDmlType instead of matching message text. Messages can change with the user's language and with admin edits to validation rules. Status codes are stable.
public class DmlErrorClassifier {
public static String classify(DmlException e) {
if (e.getNumDml() == 0) {
return 'unknown';
}
switch on e.getDmlType(0) {
when REQUIRED_FIELD_MISSING {
return 'missing-field';
}
when FIELD_CUSTOM_VALIDATION_EXCEPTION {
return 'validation';
}
when UNABLE_TO_LOCK_ROW {
return 'retryable';
}
when else {
return 'other';
}
}
}
}This checks only the first failure, which is enough for a simple triage. If one statement can fail in several ways at once, loop over all failures instead.
What gets undone, and what does not
The effect of a DmlException on your data depends on whether you catch it.
- If you catch it, the failed statement leaves no changes behind. DML statements that ran earlier in the same transaction are still pending and will commit if the transaction finishes normally.
- If you do not catch it, the whole transaction rolls back, including earlier successful DML.
The first case is a common source of partial data. Consider this code:
Account acc = new Account(Name = 'Parent');
insert acc;
try {
insert new Contact(); // LastName is required
} catch (DmlException e) {
System.debug('Contact failed: ' + e.getMessage());
}
// The Account is still saved when the transaction commits.The account stays in the database even though the contact failed. If both records must succeed together, either let the exception propagate or roll back to a savepoint, as shown in the chapter on transactions.
Failures raised by triggers
When a trigger calls addError on a record, the DML statement that fired it fails with a DmlException. The status code is FIELD_CUSTOM_VALIDATION_EXCEPTION, and getDmlMessage returns the text passed to addError. This means the code that runs DML can show or log trigger messages through the same API as platform errors.
Two details matter here:
- If a trigger fires from a DML statement inside a
tryblock, the exception reaches your catch block only if the trigger's error is attached to a record in that statement. Athrowof a custom exception from the trigger surfaces as that exception type, not asDmlException. - With a trigger on a child object, the failure can come from a record you did not insert directly. For example, a cascade or an automation may update related rows. Inspect
getDmlId(i)and the message rather than assuming the failure maps to your list.
Logging and rethrowing
A catch block that only prints a debug line hides the failure from callers. Decide whether this layer can handle the error. If it cannot, rethrow, ideally wrapped in a domain exception that keeps the cause.
public class ContactService {
public class ContactServiceException extends Exception {}
public static void createAll(List<Contact> contacts) {
try {
insert contacts;
} catch (DmlException e) {
List<String> problems = new List<String>();
for (Integer i = 0; i < e.getNumDml(); i++) {
problems.add('Row ' + e.getDmlIndex(i) + ': ' + e.getDmlMessage(i));
}
throw new ContactServiceException(
'Could not create contacts. ' + String.join(problems, '; '), e);
}
}
}The caller gets one readable message, and getCause() still returns the original DmlException for deeper inspection.
Common mistakes
- Using
getMessage()for bulk failures. It may describe only one of many failed records. Loop withgetNumDml(). - Confusing
iwith the list position. UsegetDmlIndex(i)to find the submitted record. - Matching on message text. Use
getDmlType(i)orgetDmlStatusCode(i). - Swallowing the exception. An empty catch block lets the transaction commit with missing data and leaves no trace.
- Catching
DmlExceptionfor limit problems. ALimitExceptionis not aDmlException, and a catch block cannot stop it. - Retrying everything. Only transient failures such as
UNABLE_TO_LOCK_ROWare worth retrying. A required-field failure fails again every time.
Exercise
A method runs insert acc; successfully, then runs insert contactList; inside a try block with catch (DmlException e) { System.debug(e.getMessage()); }. One contact in the list has no LastName. Method returns normally. Is the account saved? Are the valid contacts in the list saved? How would you find which contact failed?
Show answer
The account is saved, because the exception was caught and the transaction commits normally. None of the contacts are saved, because DML is all-or-none by default and the whole insert contactList; statement fails. To find the failed contact, loop from 0 to e.getNumDml() - 1 and call e.getDmlIndex(i), which gives the position of the failed record in contactList, along with e.getDmlMessage(i) for the reason.