1

I got a VF page where a user can enter many contacts and save them all in one go. I got a validation on Email field to stop the user entering duplicate values when saving records.

Therefore to catch the exception I use ex.getMessage(); where it shows in which row the duplicate value occurred for the Email.

Exception-----when using ex.getMessage

Error: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Email address already exists on another valid contact record. We recommend you use the existing record(s) instead.: []

But I want to use a custom message instead to provide a meaningful message and want to display the row number as well for the user to understand in which row the exception occurred. Help on this is much appreciated !

Controller Method

public PageReference SaveMultipleContacts(){
        try{
            AddMultipleContactsHelper.save(contList);
            ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, Label.Save_multiple_contacts_success));
            saved =true;

        }catch(Exception ex){
            ApexPages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR,ex.getMessage()));
            saved =false;
        }
        return null;
    }
  • 1
    Have you looked at getStackTraceString? – sfdcfox Nov 11 '15 at 15:03
  • DmlException EX1 = (DmlException)ex; for(Integer i = 0 ; i<ex1.getNumDml(); i++){ ApexPages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR,'Email Address on row' +' '+(EX1.getDmlIndex(i)+1)+' '+'already exists in another valid Contact record. Please use a unique Email Address' )); – Tinkerbell Nov 11 '15 at 16:34
  • above solution worked ! – Tinkerbell Nov 11 '15 at 16:35
1

Following solution worked !

DmlException EX1 = (DmlException)ex;
    for(Integer i = 0 ; i<ex1.getNumDml(); i++){
        ApexPages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR,'Email Address on row' +' '+(EX1.getDmlIndex(i)+1)+' '+'already exists in another valid Contact record. Please use a unique Email Address' ));

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.