Error handling is an important part of Salesforce Apex development. A poorly handled exception can make debugging difficult and may leave users with unclear error messages.
A good approach is to handle errors deliberately rather than simply catching every exception.
Use Try-Catch Carefully
A basic Apex pattern looks like this:
try {
update accountsToUpdate;
} catch (DmlException e) {
System.debug('Update failed: ' + e.getMessage());
}
The try block contains the operation, while the catch block handles the exception.
However, simply catching an exception is not enough.
Do Not Hide the Error
This pattern can cause problems:
try {
update records;
} catch (Exception e) {
// Do nothing
}
The transaction may fail, but nobody knows why.
Instead, capture useful information and handle the error according to the application's needs.
Use Specific Exceptions When Possible
A DmlException is more useful than a generic Exception when the problem is related to a database operation.
For example:
try {
update accountsToUpdate;
} catch (DmlException e) {
System.debug('DML Error: ' + e.getMessage());
}
Specific exception handling makes the code easier to understand and troubleshoot.
Consider Partial Success
When updating multiple records, developers may need to know which records succeeded and which failed.
Using Database.update() with allOrNone set to false can allow partial processing:
Database.SaveResult[] results =
Database.update(accountsToUpdate, false);
Developers can then inspect each SaveResult and handle individual failures.
Log Useful Information
When an error occurs, useful debugging information can include:
Exception type
Error message
Record Id
Operation being performed
Relevant business context
Avoid logging unnecessary sensitive information.
Final Thought
Good Apex error handling should help both users and developers. Users should receive a useful response, while developers should have enough information to understand what went wrong.
The goal is not simply to prevent an exception from appearing. The goal is to make failures understandable, traceable, and easier to fix.
Top comments (0)