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
Harsha ShriHarsha Shri 

DML exception on VF Page

Hi All,
I have a button on visualforce page to save records into custom object. I have created a uniqie text field and workflow to prevent duplicate values.
but, when I am clicking on save button from VF page it is throwing following error.
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []

I know this error is showing because of unique values are found while creating record.
I do not want to show this error, I want to show some standard message like already record is there. How can I handle this using apex?
please help me
Thanks in Advance
Best Answer chosen by Harsha Shri
Dmitry AleinikDmitry Aleinik
Hi, you can use <apex:message/>. Add it to your visulforce page. Then use try and catch block in your save function to catch an exception. 
public PageReference save() {
   try {   
    update account;   
    }    catch(DmlException ex){
       ApexPages.addMessages(ex);
    }
   return null;
   } 

All Answers

Dmitry AleinikDmitry Aleinik
Hi, you can use <apex:message/>. Add it to your visulforce page. Then use try and catch block in your save function to catch an exception. 
public PageReference save() {
   try {   
    update account;   
    }    catch(DmlException ex){
       ApexPages.addMessages(ex);
    }
   return null;
   } 
This was selected as the best answer
Harsha ShriHarsha Shri
Thank you very much Dmitry for your help