+ Start a Discussion
Matt Scholl 10Matt Scholl 10 

How to Handle DmlException when Converting Leads

Hi All,
I have a lead trigger that automatically converts certain Leads. We recently added a Contact Duplicate Rule that causes a DmlException when one of Leads creates a duplicate Contact.
Here is my code:

List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
List<Database.LeadConvertResult> lcrList = Database.convertLead(leadConverts);

I have tried putting the Database.convertLead in a try/catch (DmlException de) block.
I have tried setting DMLOptions.DuplicateRuleHeader.allowSave = true.
I still can't seem to trap the error: FATAL_ERROR System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?: []
Two questions:
1. How can I trap the error?
2. How can I print the error message for each failed lead conversion in the list to the debug log? System.debug('Error: '+{what?})
Thanks in advance!
Jainam ContractorJainam Contractor
Hi Matt,

You can do one thing, you can fetch all the possible contacts records for all the lead names you are dealing with. And then check if there is any duplicate then don't convert those leads and rather update the existing record.

Lead duplicates might be checked based on the Name and Company Name/ Account. So check whether there exist any duplicate contacts and if so then exclude those leads from the list and then convert the remaining ones...

Jainam Contractor
Matt Scholl 10Matt Scholl 10
Thanks for the quick response. That would probably work, but I would like to avoid writing my duplicate rules into code. I already have them defined as Duplicate Rules and Matching Rules.