Sub topic 4
Reading exception details
This chapter assumes you can write a basic try/catch/finally block and know the common built-in exception types such as QueryException and DmlException. It covers what an exception object tells you after you catch it, and how to pull that information out reliably.
What every exception carries
Every exception in Apex, built-in or custom, has the same set of methods. When code fails, these methods are your main source of diagnostic information.
| Method | Returns | Use it to |
|---|---|---|
| `getMessage()` | The error message | Show or log a human-readable reason |
| `getTypeName()` | The exception type name as a string | Log which kind of failure occurred |
| `getCause()` | The wrapped exception, or `null` | Find the original failure behind a wrapper |
| `getStackTraceString()` | The call stack as a string | See which classes and methods were running |
| `getLineNumber()` | The line number where the exception was thrown | Locate the failing statement |
| `setMessage(String)` | Nothing | Replace the message |
| `initCause(Exception)` | Nothing | Attach a cause after construction |
DmlException adds methods that report per-record detail. They are covered later in this chapter.
getMessage and getTypeName
getMessage() returns the text describing the failure. getTypeName() returns the fully qualified type name, such as System.QueryException. For a custom exception nested in a class, the name includes the outer class, such as InvoiceService.InvoiceException.
The type name is often more useful than the message in logs. Messages differ between orgs, languages, and releases. The type name is stable, so you can filter and group on it.
try {
Account a = [SELECT Id FROM Account WHERE Name = 'Does Not Exist' LIMIT 1];
} catch (Exception e) {
System.debug(e.getTypeName());
System.debug(e.getMessage());
}The first line prints System.QueryException. The second prints List has no rows for assignment to SObject.
getStackTraceString and getLineNumber
getStackTraceString() returns the call stack at the point where the exception was created. Each frame names a class, a method, a line, and a column. For example:
Class.InvoiceService.applyDiscount: line 6, column 1
AnonymousBlock: line 1, column 1The top frame is where the exception was thrown. The frames below it are the callers, ending with whatever started the transaction (a trigger, an anonymous block, a test method, and so on).
getLineNumber() returns just the line number of the top frame. This is handy for a short log entry. The stack trace is better for diagnosis, because the top frame is often a shared utility and the real mistake is in a caller.
Walking the cause chain
When code wraps one exception in another, the original failure is available through getCause(). The wrapper's own stack trace points at the place where it was created. The original line number and type live on the cause.
A cause can have its own cause, so one call to getCause() may not reach the root. The helper below walks the whole chain and builds one readable string.
public class ErrorFormatter {
public static String describe(Exception e) {
List<String> lines = new List<String>();
Exception current = e;
Integer depth = 0;
while (current != null && depth < 10) {
lines.add('[' + depth + '] ' + current.getTypeName() + ': ' + current.getMessage());
lines.add(' line ' + current.getLineNumber());
lines.add(' ' + current.getStackTraceString());
current = current.getCause();
depth++;
}
return String.join(lines, '\n');
}
}Two details matter here. getCause() returns null when there is no cause, so the loop condition checks for it. The depth cap of 10 is a guard against a malformed chain, so the loop cannot run forever.
Use it like this:
try {
insert new Account();
} catch (DmlException e) {
System.debug(ErrorFormatter.describe(e));
}For a plain DmlException the output has one entry, because nothing wrapped it. If the exception had been wrapped by a service class, as in AccountService.create, you would see the wrapper first ([0]) and the DmlException second ([1]).
Per-record detail from DmlException
A DML statement can touch many records, and getMessage() for a DmlException reports only the first failure in a summary form. To see each failed record, use the indexed methods.
| Method | Returns |
|---|---|
| `getNumDml()` | The number of failed records |
| `getDmlIndex(i)` | The position, in the original list, of the i-th failed record |
| `getDmlFieldNames(i)` | A list of field names tied to the i-th failure |
| `getDmlMessage(i)` | The error message for the i-th failure |
| `getDmlStatusCode(i)` | The status code string, such as `REQUIRED_FIELD_MISSING` |
| `getDmlType(i)` | The `StatusCode` enum value for the i-th failure |
| `getDmlId(i)` | The record Id for the i-th failure, when one exists |
The argument i runs from 0 to getNumDml() - 1. It indexes the list of failures, not the list of records you submitted. To map a failure back to your input, call getDmlIndex(i).
List<Account> accts = new List<Account>{
new Account(Name = 'Valid'),
new Account()
};
try {
insert accts;
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
Integer originalPosition = e.getDmlIndex(i);
System.debug('Row ' + originalPosition + ' failed: '
+ e.getDmlStatusCode(i) + ' ' + e.getDmlFieldNames(i)
+ ' ' + e.getDmlMessage(i));
}
}The loop finds one failure, and getDmlIndex(0) returns 1, the position of the account with no name. A plain insert is all-or-none, so the valid account at position 0 is also not saved.
A DmlException thrown from a trigger or a validation rule gives the same per-record detail. Failures that happen outside your code, such as a duplicate rule, also show up here.
Changing or attaching information
setMessage(String) replaces the message that getMessage() returns. Use it sparingly. The case where it matters is AuraHandledException, where the message you set is the one a Lightning component shows. The Aura chapter covers this.
initCause(Exception) attaches a cause to an exception that was built without one. In most code, pass the cause to the constructor instead. Every custom exception you declare gets constructors that accept a message, a cause, or both.
public class AccountService {
public class AccountServiceException extends Exception {}
public static void create(Account acc) {
try {
insert acc;
} catch (DmlException e) {
throw new AccountServiceException('Could not create account', e);
}
}
}A caller that catches AccountServiceException can then call getCause() and cast it to DmlException to reach the per-record methods.
try {
AccountService.create(new Account());
} catch (AccountService.AccountServiceException e) {
if (e.getCause() instanceof DmlException) {
DmlException dml = (DmlException) e.getCause();
System.debug(dml.getDmlMessage(0));
}
}The instanceof check is required. A cause can be any exception type or null, and a cast on the wrong type throws a TypeException.
Common mistakes
- Logging only
getMessage(). The message has no location. Log the type name and stack trace too, or you cannot tell where a failure started. - Calling
getCause()once and assuming it is the root. Walk the chain, as inErrorFormatter. - Calling
getDmlMessage(i)on a non-DML exception. Those methods exist only onDmlException. Catch that type, or check withinstanceofand cast. - Using
getDmlIndexand the loop counter as if they were the same. The loop counter indexes failures.getDmlIndex(i)indexes your input list. - Showing raw messages to end users.
getMessage()can contain internal field names and Ids. Convert it to a friendly message before returning it to a UI.
Exercises
Exercise
A service class catches a DmlException and throws new OrderException('Order failed', e). A caller catches OrderException and wants the name of the field that caused the failure. Which calls does it need, and what check should it make first?
Show answer
The caller calls getCause() and checks instanceof DmlException. If the check passes, it casts the cause to DmlException and calls getDmlFieldNames(0), or loops from 0 to getNumDml() - 1. The check is needed because getCause() may return null or a different exception type, and the DML methods exist only on DmlException.
Exercise
You run insert on a list of five accounts, and getNumDml() returns 2 in the catch block. For the second failure, getDmlIndex(1) returns 3. What does each number tell you, and how many of the five accounts were saved?
Show answer
getNumDml() returns 2, so two records failed. getDmlIndex(1) returns 3, so the second failure is the account at position 3 (the fourth) in the original list. A plain insert is all-or-none, so none of the five accounts were saved.