I'm writing code to upload attachment. I've written follow code around insert statement in my controller extension

     insert att; 
  catch(exception e) {
      apexpages.message msg = new apexpages.message(apexpages.severity.fatal, 'Required Fields are missing.Code has some issue');
      apexpages.addmessage(msg );

I was expecting only above error message(Required Fields are missing.Code has some issue) will be visible in my

<apex:pagemessages />

But it is also showing system error message

Error: Required fields are missing: [Parent]

which i don't want to be shown, when error occcur on page.

what should i do to avoid this and to make sure page shows only, custom error message provided by me ?


In a VF context, an error generated by a Validation Rule or a required field missing rule will already exist in the apexPages.getMessages() list.

Hence, in your catch block, you are duplicating the message already placed there by the implicit database validation rules run by SFDC.

One way around this (since other errors like attempt to de-reference a null object won't already be in apexpages.getmessages()) is to use some common handler within your catch block that compares the exception's message with the contents of apexpages.getMessages() to see if it is a duplicate and then ignore

try { ..}
catch (Exception e) {

// rough version of an VF exception handler.. fine-tuning may be
// required to get the results you want
public static void myVfExceptionhandler(Exception e) {
  if (ApexPages.hasMessages() && 
      Apexpages.getMessages[ApexPages.getMessages().size()-1].getMessage ==
      e.getMessage() {} // or use containsIgnorecase(..)
      apexpages.addMessage(new apexpages.message(
  • What if you want to hide the system-generated error and only show the custom error message? – Jeremy Nottingham May 10 '15 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.