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
Ankur SrivastavaAnkur Srivastava 

Duplicate rule error message to display on custom lead convert page

There is a duplicate rule on Account object enabled in my org. I have a customize lead convert classic page, in which if I select Create New account option then on click of convert button, it should display the error message of the duplicate rule. I added the below code to be displayed in error messge.
Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvert);
        
        // if the lead converting was a success then create a task
        if (!leadConvertResult.success)
        {
           PrintErrors(leadConvertResult.errors);
            
            return null;
         }

    //this method will take database errors and print them to teh PageMessages 
    public void PrintErrors(Database.Error[] errors)
    {
        for(Database.Error error : errors)
        {
            if(error instanceof Database.DuplicateError)
            {
               Database.DuplicateError duplicateError = (Database.DuplicateError)error;
               Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();
			// Display duplicate error message as defined in the duplicate rule
               ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.Severity.ERROR, 'You are creating a duplicate record. We recommend you use an existing record instead.');
               System.debug('The error message'+errorMessage);
                ApexPages.addMessage(errorMessage); 
            }
        }
    }
The above code doesn't provide the simple error message as mentioned in the code. However I recieve a the below error. What is it that I am doing wrong here ?
Best Answer chosen by Ankur Srivastava
~Onkar~Onkar
Use Try and Catch block and show your error message in exception block.

~Thanks,
Onkar Kumar

All Answers

Ankur SrivastavaAnkur Srivastava
Error on lead conversion due to duplicate accounts
Above is the error snapshot.
~Onkar~Onkar
Use Try and Catch block and show your error message in exception block.

~Thanks,
Onkar Kumar
This was selected as the best answer
Ankur SrivastavaAnkur Srivastava
Thanks it worked.