function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mak OneMak One 

Is there any good way provided by Salesforce to catch Validation Error?

I have seen suggestion with below code for catching Validation Error:

try {
   update user;
}
catch (Exception e) {
   String errorMessage = e.getMessage();
   if(!errorMessage.contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, errorMessage));
   }
}

Is there any better way for this as my custom error message may also contain String: 'FIELD_CUSTOM_VALIDATION_EXCEPTION'

Is there any specific Exception Type provided by Salesforce for Validation Error. Or is there any better way to catch ValidationError?

praveen murugesanpraveen murugesan
Hello Mak,

You can use this way to show a proper error message on validation exception
if(e.getMessage().Contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'))
{
     ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,+e.getMessage().substringAfter('EXCEPTION,').substringBefore(': []')));
}
--

Praveen Murugesan
Mark this as best answer if its helps.