Andy in the Cloud

From BBC Basic to Force.com and beyond…

Hidden Gem no longer Hidden! Database.Error.getFields

3 Comments

hiddengemA 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());
    }
}

3 thoughts on “Hidden Gem no longer Hidden! Database.Error.getFields

  1. What’s up i am kavin, its my first occasion to commenting anyplace, when i read this post i thought i could also
    make comment due to this brilliant article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s