Improve Apex Testing with New SObject Error Methods

Track errors with the new SObject.hasErrors() and SObject.getErrors() methods without performing a DML operation to check the result for errors. Dynamically add errors to specific fields with new SObject.addError() overload methods. Use the hasErrors() method to know if an SObject instance contains errors. Use the getErrors() method to retrieve the list of errors for a specific SObject instance.

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How: 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.

This example code shows usage of the new SObject error methods.

//Baseline code sample for using addError, getErrors, together
   Account a = new Account();
   String msg = 'New error method in SObject';
   //The new overload that accepts the field dynamically at runtime
   a.addError('Name', msg); 
   List<Database.Error> errors = a.getErrors();
   System.assertEquals(1, errors.size());
   Database.Error error = errors.get(0);
   System.assertEquals(msg, error.getMessage());
   System.assertEquals(StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, error.getStatusCode());
   String[] fields = error.getFields();
   System.assertNotEquals(null, fields);
   System.assertEquals(1, fields.size());