6
votes

I have added few custom validations using Configuration for an object. I am inserting that object record through visualforce page. I have added <apex:pageMessages/> on my visualforce page. I have also written code block for catching the exception and to show the error message ob VF page. Please find code block below :

catch(DMLException excp)
{
    ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, excp.getMessage() );
    ApexPages.addMessage(msg);  
    return null;                            
} 

Still I am not able to get only error message from the custom validation. It shows me error like below :

Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, error_message_from_custom_validation_comes_here

Is there any solution for this?

4

4 Answers

9
votes

You need to get the DML message like so:

ApexPages.Message msg = new ApexPages.Message(Apexpages.Severity.ERROR, excp.getdmlMessage(0) );
ApexPages.addMessage(msg);

Using Exception Messages

5
votes

The best way is to use addMessages, notice the plural. It has the advantage of showing only the message detail, and for bulk operations the same message is shown only once, and my personal favourite: it's only one line so if it's an untestable exception your coverage is higher.

try {
    //failed dml operation
} catch(DmlException excp) {
    ApexPages.addMessages(excp);
}
2
votes
try{
   ...
} catch (DMLException ex){
    String errorMessage = ex.getMessage();
    Integer occurence;
    if (ex.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
        occurence = errorMessage.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION,') + 34;
        errorMessage = errorMessage.mid(occurence, errorMessage.length());
        occurence = errorMessage.lastIndexOf(':');
        errorMessage = errorMessage.mid(0, occurence);
    }
    else {
        errorMessage = ex.getMessage();
    }

    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, errorMessage));
}
0
votes

By using one more string function to Miguel's code will give you exact "validation error message". Thank you Miguel. Your code helped me. Hope this helps.

str = errorMessage.substringBefore(':');