Sub topic 16
Designing a consistent error-handling approach
This chapter assumes you know try, catch, and finally, custom exception classes, DML error handling, savepoints, AuraHandledException, and basic Apex tests. It pulls those pieces into one set of rules you can apply across a codebase.
Decide where to catch
Every exception has one best place to be handled. Catch it only where you can do something useful: recover, add context, roll back, or translate it for a caller. Anywhere else, let it propagate.
| Situation | Action |
|---|---|
| You can recover (use a default, retry, skip a record) | Catch and continue |
| You can add meaning (which record, which step) | Wrap in your own exception with the cause |
| You must undo partial work | Catch, roll back to a savepoint, rethrow |
| The caller is a Lightning component | Catch at the controller and throw AuraHandledException |
| Nothing useful can be done | Do not catch |
Use one exception type per layer
Give each service its own exception class. Callers then catch one type instead of guessing which low-level exceptions might appear. Always pass the original exception as the cause so the stack trace and details survive.
public class OrderService {
public class OrderServiceException extends Exception {}
public static void place(Order o) {
Savepoint sp = Database.setSavepoint();
try {
insert o;
} catch (DmlException e) {
Database.rollback(sp);
throw new OrderServiceException('Could not place order: ' + e.getMessage(), e);
}
}
}Translate only at the boundary
Convert to AuraHandledException in the controller, not in the service. The service stays reusable from triggers, batch jobs, and tests, and only the controller knows about the user interface.
public with sharing class OrderController {
@AuraEnabled
public static void placeOrder(Order o) {
try {
OrderService.place(o);
} catch (OrderService.OrderServiceException e) {
AuraHandledException ex = new AuraHandledException(e.getMessage());
ex.setMessage(e.getMessage());
throw ex;
}
}
}Common mistakes
- Empty catch blocks. Swallowing an exception hides the failure and leaves the transaction looking successful. At minimum, log it and rethrow.
- Catching generic Exception everywhere. Use it only as a last catch block, after specific types, or at a top-level boundary such as an asynchronous job's
executemethod. - Losing the cause. Throwing a new exception without the original removes the stack trace you need to debug.
- Catching what you cannot catch. Limit exceptions such as too many SOQL queries cannot be caught. Prevent them by bulkifying code.
- Showing raw messages to users. Technical text confuses users. Log the detail and show a short, actionable message.
A short checklist
- Does this catch block recover, add context, roll back, or translate? If not, remove it.
- Is the cause preserved when wrapping?
- Is partial work rolled back or deliberately kept?
- Does the asynchronous job record its failure somewhere visible?
- Does a test prove the failure behavior?
Exercise
A service method inserts a record inside a try block. The catch block catches Exception and only calls System.debug. What two problems does this cause, and how would you fix them?
Show answer
It swallows the failure, so the caller and the transaction treat the operation as successful, and it loses the specific exception type. Fix it by catching DmlException specifically, rolling back to a savepoint if partial work exists, and throwing a service-specific exception that passes the original as the cause.
Exercise
Why should the AuraHandledException be thrown in the controller instead of the service class?
Show answer
The service is also used by triggers, batch jobs, and tests, which have no Lightning user interface. Keeping the translation in the controller leaves the service reusable and confines user-interface concerns to the boundary.