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
John Neilan 18John Neilan 18 

Show Apex Errors on Visualforce Page

Hi,

I have a VF page with a custom controller that allows a user to enter multiple records for a custom object using a Type picklist field. I also have a trigger that populates those values to the parent record (Contact) and only allows 1 of each Type for the child records. If there are duplicates, an error message is thrown.

Currently, the error message shows as an non user-friendly messge on the page:
 
Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, This Type already exists for this Contact: []
Error is in expression '{!saveType}' in component <apex:commandButton> in page newrectype: Class.NewRecController.saveType: line 46, column 1

An unexpected error has occurred. Your development organization has been notified.

What can I do to get this message to show on the VF page at the top as a simple message like "This Type already Exists"?

My Save method is below and I do have <apex:pageMessages> in my VF page.
 
public PageReference saveType() {
    	insert listRecType;
        PageReference contRecord = new PageReference('/'+contId);
        contRecord.setRedirect(true);
    return contRecord;
    }

 
Best Answer chosen by John Neilan 18
John Neilan 18John Neilan 18
I was able to get what I needed by adding a Try/Catch block to my method.  The new method is:
 
public PageReference saveType() {
    	try {
        	insert listRecType;
    	} catch(DmlException e) {
        	ApexPages.addMessages(e);
        return null;
    	}
        PageReference contRecord = new PageReference('/'+contId);
        contRecord.setRedirect(true);
    return contRecord;
    }

 

All Answers

VinayVinay (Salesforce Developers) 
Hi John,

I am afraid you cannot do this Because these are system generated error by the backend server and you do not have control or customize the error message.

Thanks,
Vinay Kumar
John Neilan 18John Neilan 18
I was able to get what I needed by adding a Try/Catch block to my method.  The new method is:
 
public PageReference saveType() {
    	try {
        	insert listRecType;
    	} catch(DmlException e) {
        	ApexPages.addMessages(e);
        return null;
    	}
        PageReference contRecord = new PageReference('/'+contId);
        contRecord.setRedirect(true);
    return contRecord;
    }

 
This was selected as the best answer