I have a VF page and custom controller on a custom object related to the Contact object. There is also a trigger on the custom object that prevents duplicate entries. All works fine, however, when a user enters a duplicate value for the custom object record, they get an Apex error:

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 newtype: Class.NewController.saveType: line 36, column 1

Is there any way to show this as a more user-friendly message on the resulting VF page?


Yes, you can catch those errors:

try {
  insert record;
} catch(Exception e) {

Or you can manually process them:

Database.SaveResult[] results = Database.insert(new sObject[] { record }, false);
if(!results[0].isSuccess()) {
  ApexPages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.ERROR, results[0].getErrors()[0].getMessage()));
  • Thanks. I'm not really trying to catch the error, but more to make it a more user-friendly error. Right now is appear as a typical Apex error because the duplicate checking is done in the trigger. Is there a way to re-format the error or show a more simplified message? – J. Neilan Sep 21 '20 at 18:49
  • @J.Neilan Yes, you could make it however you'd like. I typically just use ApexPages.addMessages, but you have full control over your logic, so you can make it look however you want. – sfdcfox Sep 21 '20 at 18:51

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.