I have the following duplicate rule:
I have Allow
ed Action on create
and Action on edit
but when I try to create a duplicate account in apex, I get an error:
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?: []
I can try to capture it using the following try/catch
but is there a more elegant way to check if a duplicate rule is hit or not?
Also, is there a way to detect the duplicate record found inside the catch
? (Note I'm getting an empty array in the error)
Account a = new Account();
a.Name = 'Some account';
a.BillingCity='City';
a.BillingState='State';
a.BillingStreet ='Street';
a.BillingPostalCode='123';
try{
insert a;
} catch(DMLException e){
if(e.getMessage().contains('DUPLICATES_DETECTED')){
//------DO SOMETHING HERE------
System.debug('if');
}
System.debug(e);
}
Best Answer
Yes, the example is in the documentation.
Basically, you can use allOrNone = false, and examine the errors. It includes which rules caused the error, and the matches that were found.