Amit Chaudhary

Amit Chaudhary

Amit Chaudhary is Salesforce Application & System Architect and working on Salesforce Platform since 2010. He is Salesforce MVP since 2017 and have 17 Salesforce Certificates. He is a active blogger and founder of Apex Hours.

Improve Apex Testing with New SObject Error Methods

Basically this Winter 21 update for improve test class error methods. Salesforce introduce two new methods SObject.hasErrors() and SObject.getErrors(). With this methods we can track errors without performing a DML operation to check the result for errors. Dynamically add errors to specific fields with new SObject.addError() overload methods.

There are really three new sObject methods to keep in mind here addError(),  getErrors()  and  hasErrors().

  1. SObject.addError() : Marks a trigger record with a custom error message and prevents any DML operation from occurring and Dynamically add errors to specific fields with new SObject.addError() overload methods.
  2. SObject.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.
  3. SObject.getErrors() : Returns a list of Database.Error objects for an SObject instance. If the SObject has no errors, an empty list is returned.

Check all other methods here.

Sample Code for SObject Error Method

private class TestClassDemo {
    public static void testAddErroMethd() {
       //Baseline code sample for using addError, getErrors, together
       Account a = new Account();
       String msg = 'Demo = New error method in SObject';
       a.addError('Name', msg); 

       List<Database.Error> errors = a.getErrors(); // Get Error
       System.assertEquals(1, errors.size()); // Assert Result

       Database.Error error = errors.get(0);
       System.assertEquals(msg, error.getMessage()); // Validate message
       System.assertEquals(StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, error.getStatusCode());


If the SObject.addError() method has been called on an SObject instance, the SObject.hasErrors() method returns true. The SObject.getErrors() method returns a list of Database.Error objects that contain the errors encountered.

Further Learning

Share this article

Leave a reply

Keep in Touch

Subscribe for Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,229 other subscribers


Our Supporter


Apex Hours

Apex Hours is one stop platform to learn Salesforce skills and technology

Join our Newsletter and get tips and tricks how to explore the salesforce for free!