2

I am implementing a partner product that after it has an insertion of a record into a history object, it then needs to update the referring lead record. Most of the time it works without issue, but if this lead was just converted, then obviously I can't reference the lead otherwise an error will be thrown. Is there a specific exception I need to be catching?

Here is the error received:

CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: []

Below is my exception handling block:

try
{
    update leadsToUpdate;
}
catch (DmlException ex)
{
    System.debug('Attempt to update leads failed: likely due to referencing converted leads: ' + ex);
}

Thanks so much in advance, BY

1 Answer 1

2

Rather than catching the exception, you could just filter out all leads that have been converted. In the query where you initially populate the leadsToUpdate list, simply add this to the Where Clause: "IsConverted = false". This will ensure you are not trying to update a lead that is already converted.

Select Id, MyField__c From Lead Where Id IN :leadIds And IsConverted = false

You could also modify your code to update the Account/Contact record instead of the lead record if this is the required behavior.

List<Lead> convertedLeads = [Select Id, ConvertedContactId From Lead Where Id IN :leadIds And IsConverted = true];
Set<Id> contactIds = new Set<Id>();
for (Lead ld : convertedLeads) {
  contactIds.add(ld.ConvertedContactId);
}
List<Contact> contactsToUpdate = [Select Id, MyField__c From Contact Where Id IN :contactIds];

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .