Sub topic 16
Designing a Consistent Error-Handling Approach
Earlier chapters covered the mechanics: try, catch, finally, custom exceptions, causes, DML errors, savepoints, AuraHandledException, and tests. This chapter combines them into one approach you can apply across a codebase.
This chapter assumes you can read and write basic Apex classes and know how SOQL, DML, and transactions behave. It also assumes you have seen the exception types and methods from the earlier chapters.
Why consistency matters
Each developer's local choices add up. One method returns null on failure. Another catches Exception and logs nothing. A third lets a raw DmlException reach the user. Callers then cannot tell what a method does when it fails.
A consistent approach answers three questions the same way everywhere:
- Who is allowed to catch this error?
- What type does the caller see?
- Is the data left in a known state?
Assign a role to each layer
Most Apex applications have three layers. Each layer has one job when something fails.
- Data and DML code lets built-in exceptions travel upward. It does not translate or hide them.
- The service layer owns the business rules and the transaction. It validates input, rolls back partial work, and throws one custom exception type with the original error as the cause.
- The boundary is a controller, a REST resource, or a queueable's
executemethod. It catches the service exception and converts it for the caller. A controller throwsAuraHandledException. A queueable logs the failure.
Decide: catch, wrap, rethrow, or propagate
Apply this table each time you write a catch block.
| Situation | Action | Reason |
|---|---|---|
| You can recover and continue, for example by using a default value | Catch the specific type | The error is handled, so nothing needs to escape |
| The error is a low-level detail the caller should not know about | Wrap in your own exception and pass the cause | Callers depend on one stable type, and the stack is preserved |
| You must clean up but cannot fix the problem | Clean up, then rethrow | The caller still learns the operation failed |
| You have nothing useful to add | Do not catch it | The exception propagates and the transaction rolls back |
| You are at a boundary | Translate, and log if the error would otherwise vanish | This is the last place that can act on it |
The last row of the table needs one clarification. A failure must always end in one of three outcomes: it is handled, it is shown to the user, or it is recorded for someone to find later. If none of these happens, you have swallowed it.
Build the service layer
This service shows the pattern in code. It defines one exception type, validates input, and rolls back with a savepoint when the second insert fails.
public with sharing class OnboardingService {
public class OnboardingException extends Exception {}
public static Id onboard(String accountName, String contactLastName) {
if (String.isBlank(accountName)) {
throw new OnboardingException('Account name is required.');
}
Savepoint sp = Database.setSavepoint();
try {
Account acc = new Account(Name = accountName);
insert acc;
insert new Contact(LastName = contactLastName, AccountId = acc.Id);
return acc.Id;
} catch (DmlException e) {
Database.rollback(sp);
throw new OnboardingException(
'Onboarding failed: ' + e.getDmlMessage(0), e
);
}
}
}Three design decisions are visible here:
- Validation throws before any work starts. The caller gets a clear message and nothing has changed in the database.
- The catch block is narrow. It catches
DmlException, notException, so programming errors such as aNullPointerExceptionstill surface as bugs. - The savepoint is deliberate. An uncaught exception rolls back the whole transaction on its own. The savepoint matters because a caller further up might catch your exception and keep going. Without the rollback, the Account would remain saved with no Contact.
Translate at the boundary
The controller is the one place that turns a service exception into something a Lightning component can display.
public with sharing class OnboardingController {
@AuraEnabled
public static Id onboard(String accountName, String contactLastName) {
try {
return OnboardingService.onboard(accountName, contactLastName);
} catch (OnboardingService.OnboardingException e) {
AuraHandledException ae = new AuraHandledException(e.getMessage());
ae.setMessage(e.getMessage());
throw ae;
}
}
}The controller has no business logic and no DML. It catches only the service's exception type. If something unexpected escapes the service, such as a NullPointerException, the controller does not hide it. That is intentional, because an unexpected failure should look like one.
Messages from AuraHandledException are shown to end users. Write them in plain language and leave out record Ids, field API names, and stack details. Put technical detail in the cause and the logs.
Choose where logging happens
Log once, at the point where the exception stops moving upward. If every layer logs and rethrows, one failure produces three entries and a reader cannot tell how many errors occurred.
- In a service that rethrows, do not log. Pass the cause instead.
- At a boundary that swallows the error, such as a batch
executethat continues with the next record, always log. - Record
getTypeName(),getMessage(), andgetStackTraceString(). WalkgetCause()too, because the original error is often the useful one.
System.debug is not logging for production purposes. Debug logs are short-lived and often switched off. Use a custom object, a platform event, or a logging framework your team already has.
Treat batch and async code as boundaries
Asynchronous code has no user to show an error to. If the exception escapes execute, the job fails and the only trace is a notification or a row in Apex Jobs. The usual design is:
- Queueable and Batch: Catch at the
executelevel, log the failure, and decide whether to rethrow. For batches, useDatabase.update(records, false)when one bad record should not block the others, and log each failedSaveResult. - Governor limit errors:
System.LimitExceptioncannot be caught. Prevent it with bulk-safe design, because nocatchblock can recover from it.
Common mistakes
- Catching
Exceptionfirst. This hides bugs and blocks more specific handlers placed after it. Put specific types first and useExceptiononly at a boundary. - Empty catch blocks.
catch (Exception e) {}makes failures invisible. At minimum, log. - Losing the cause.
throw new MyException(e.getMessage())discards the original stack trace. Passeas the second argument. - Using exceptions as control flow. Check
String.isBlank(value)orlist.isEmpty()instead of waiting for an exception. - Returning error codes or
null. Callers forget to check them. An exception cannot be ignored by accident. - Throwing
AuraHandledExceptionfrom a service. This ties a business class to the UI. Keep it in controllers.
Test the design
A consistent design is easy to test, because each layer has a predictable failure. Test that the service throws its own type, keeps the cause, and leaves no data behind.
@IsTest
private class OnboardingServiceTest {
@IsTest
static void rollsBackWhenContactFails() {
try {
OnboardingService.onboard('Acme Test', null);
Assert.fail('Expected OnboardingException was not thrown');
} catch (OnboardingService.OnboardingException e) {
Assert.isNotNull(e.getCause(), 'The cause should be preserved');
Assert.areEqual('System.DmlException', e.getCause().getTypeName());
}
Integer remaining = [SELECT COUNT() FROM Account WHERE Name = 'Acme Test'];
Assert.areEqual(0, remaining, 'The savepoint rollback should remove the Account');
}
}The Assert.fail call raises an AssertException. The catch block does not match that type, so the test fails if the service does not throw. The final query confirms the state guarantee, not only the exception type.
A short checklist
Use this list in code review:
- Does each service expose one custom exception type?
- Does every wrapping
throwpass the cause? - Is every
catchspecific, except at a boundary? - Is every swallowed error logged?
- Do partial failures either roll back or report per record?
- Do user-facing messages hide technical detail?
- Is there a test for each failure path?
Exercise
A service method catches a DmlException and runs throw new ReportException('Save failed');. Name two problems with this, and give the corrected line.
Show answer
The original exception is lost, so the stack trace and the DML field messages are gone. The message also gives no detail about why the save failed. The corrected line is throw new ReportException('Save failed: ' + e.getDmlMessage(0), e);, which adds detail and passes the DmlException as the cause.
Exercise
A batch class's execute method updates 200 records with update records; inside a try block that catches Exception and does nothing. What happens to the failed records, and how would you redesign it?
Show answer
A single bad record throws a DmlException, the whole update rolls back, and the empty catch hides it, so no record is saved and nobody is told. Use Database.update(records, false), loop through the SaveResult list, and log each failure with its errors. Valid records are then saved and failed ones are recorded.