Quantcast
Viewing all articles
Browse latest Browse all 119

Hidden Gem no longer Hidden! Database.Error.getFields

Image may be NSFW.
Clik here to view.
hiddengem
A little while ago a developer I was working with found something undocumented in Apex. While it was a great find and very much what we needed at the time to achieve our goal to generically log errors from a Database.insert. Undocumented features can come back to bite you! For starters they are not supported and worse still can change without notice. I decided to raise a support case anyway, as it may have been a documentation oversight. The result is a few months later after a bit of testing, Salesforce have documented it and all is well! And whats more its available now!

This feature relates to an Apex class called Database.Error, used by the methods on the Database class. When performing DML operations (such as insert, update or delete for example) with a set of records the default behaviour is to fail the entire operation if any one of the records is in error .

In our case we wanted to allow valid records through and log errors for those that failed. Thus we passed false to the second parameter of the Database.insert method. The information we got back was useful but critically lacked the fields in error, leaving the user to decipher the field causing the error from the messages. The much needed getFields method returns a list of the field/s associated with the error message.

This method has now been documented, many thanks to Apex Product Manager Josh Kaplan and his team, enjoy!

List<Database.SaveResult> saveResults = Database.insert(recordsToInsert, false);
for(Database.SaveResult saveResult : saveResults)
{
    if(saveResult.isSuccess())
        continue;
    for(Database.Error err : saveResult.getErrors())
    {
        System.debug('The following error has occurred.');
        System.debug(err.getStatusCode() + ': ' + err.getMessage());
        System.debug('Fields in this error: ' + err.getFields());
    }
}

Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 119

Trending Articles