I'm working on a cleanup of some older apex code, and I've noticed two distinct patterns being used to handle errors when saving records.
One uses a try-catch block to try to update the records, and displays the exception to the page if any is caught.
try {
update accounts;
} catch (Exception e) {
ApexPages.addMessages(e);
}
The other uses the Database
class to get a result, and then iterates over the results of a insert/update operation and displays the error onto the page.
Database.SaveResult result = Database.Update(accounts, true);
if (!result.isSuccess()) {
for (Database.Error err:result.getErrors()) {
ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, err.getMessage()));
}
}
Which of these two patterns is more efficient?
Database.Update
withallOrNothing
= false when I'm allowing for partial successes; otherwise I use the try-catch – cropredy Mar 2 '16 at 17:26