I'm wondering about the documentation for the sObject class (API 50).

It clearly states this for hasErrors():

Returns true if an SObject instance has associated errors. The error message can be associated to the SObject instance by using SObject.addError(), validation rules, or by other means.

However this is not the actual behavior.

I've tested three scenarios:

  1. Validation rule on Account with error location "top of page". Fire if Account.Description is blank
  2. Validation rule on Account with error location "Name". Fire if Account.Name contains a "2"
  3. Add error in Account trigger through Apex by calling: Trigger.new[0].addError('PHONE!'); if Account.Phone is null

When I perform DML on an account that matches the scenarios, the "hasErrors" method does not behave as described. Here's my test case:

    insert acc;
catch(Exception ex)
    System.debug('Has Errors: ' + acc.hasErrors());
    System.debug('Msg: ' + ex.getMessage());

and I tested the above mentioned scenarios with this input and the corresponding result:

// hasErrors() = FALSE but DmlException message about missing description
Account acc1 = new Account(Name = 'Test', Phone = '123');

// hasErrors() = TRUE and error message about no "2" allowed in Account.Name
Account acc2 = new Account(Name = 'Test2', Phone = '123');

// hasErrors() = FALSE but DmlException message about missing phone
Account acc3 = new Account(Name = 'Test2');

As you can see only the second scenario where an error is tied to an sobject's FIELD results in sObject.hasError() to be true. When the error is only tied to the entire object and not to a field, it always returns false. According to the documentation this should not be the case. The same applies for sObject.getErrors() - for scenarios #1 and #3 it returns an empty array and is also documented otherwise.

Am I doing something wrong here or is this a bug?

I know I could get extract the errors for #1 and #3 from the DML exception but this would be much more implementation effort and I'd rather use the system in place...


You must log in to answer this question.

Browse other questions tagged .