How to show only extracted error message from Custom Validation on a Visualforce Page?
Asked Answered
P

4

6

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?

Polyzoarium answered 23/7, 2012 at 5:41 Comment(0)
J
9

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

Jardena answered 23/7, 2012 at 6:16 Comment(0)
M
5

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);
}
Mythical answered 23/7, 2012 at 21:26 Comment(1)
this is a great answer! never knew about thisJedjedd
G
2
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));
}
Goatee answered 7/4, 2014 at 15:14 Comment(0)
E
0

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(':');
Elanorelapid answered 30/7, 2015 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.