Sub topic 3
Partial Success and Reliable Error Handling in Apex
Assume you know Apex classes, SOQL, DML, transactions, and governor limits. This chapter focuses on choosing the right failure behavior for synchronous, Lightning, and asynchronous code.
Partial success with `Database.insert`
Database.insert(records, false) attempts every record. Successful records are saved, while failed records return errors in Database.SaveResult. The operation does not throw a DmlException for ordinary record-level failures.
List<Account> accounts = new List<Account>{
new Account(Name = 'Valid'),
new Account()
};
List<Database.SaveResult> results = Database.insert(accounts, false);
for (Database.SaveResult result : results) {
if (!result.isSuccess()) {
for (Database.Error error : result.getErrors()) {
System.debug(error.getStatusCode() + ': ' + error.getMessage());
}
}
}Use this approach when each record can succeed independently. Use ordinary DML when the whole operation must succeed or fail together.
Limits, rollback, and user errors
Some governor limit failures, such as exceeding a SOQL or CPU limit, raise LimitException. Apex cannot catch these exceptions. Prevent them by bulkifying code, reducing queries, and checking limits during design.
A savepoint lets you undo earlier work in the current transaction:
Savepoint point = Database.setSavepoint();
try {
Account account = new Account(Name = 'Parent');
insert account;
insert new Contact(AccountId = account.Id);
} catch (DmlException error) {
Database.rollback(point);
throw error;
}Rollback restores database changes made after the savepoint. It does not undo external actions, such as an HTTP request.
For Lightning components, expose a readable message with AuraHandledException:
@AuraEnabled
public static void saveAccount(Account account) {
try {
insert account;
} catch (DmlException error) {
AuraHandledException response =
new AuraHandledException('The account could not be saved.');
response.setMessage('The account could not be saved.');
throw response;
}
}Asynchronous Apex and testing
Queueable and Batch Apex errors should be caught inside the job when recovery or logging is possible. An uncaught error marks the asynchronous job as failed. Inspect AsyncApexJob for job status and error details. Do not rely on a synchronous caller to catch an asynchronous exception.
Test expected exceptions explicitly:
@IsTest
static void rejectsInvalidDiscount() {
try {
InvoiceService.applyDiscount(100, 150);
Assert.fail('Expected exception was not thrown');
} catch (InvoiceService.InvoiceException error) {
Assert.isTrue(error.getMessage().contains('between 0 and 100'));
}
}Design each service to catch errors it can handle, wrap low-level errors when adding useful context, and rethrow errors it cannot resolve. Log diagnostic details, but return only safe, actionable messages to users.
Exercise
When should you use SaveResult instead of catching DmlException?
Show answer
Use SaveResult when records may succeed independently and you need to inspect each record's result.