You need to sign in to do that
Don't have an account?
rcardoso
Get de existing ID from a DmlException: DUPLICATE_VALUE
Hi!
I'm trying to get the existing ID when a DmlException: DUPLICATE_VALUE is throw.
but i'm getting null.
my code looks like this:
Case c = new Case(); //set some fields try{ insert c; }catch(DmlException e){ if(e.getDmlType(0) == StatusCode.DUPLICATE_VALUE){ return e.getDmlId(0); //its null here! =( }else{ throw e;
} } return c.id;
I could to put a
c = [Select id from Case where other_fields = other_values];
but i can't be sure if it will get the same record.
If I check the logs i find:
System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: Claim_id__c duplicates value on record with id: 500J0000001ylwB: []
Any ideas how do i get the id without manipulating the message string?
500J0000001ylwB
You could call getDmlFields to determine the fields which failed. From there, you could construct a query to find the duplicated value (SELECT Id FROM Case WHERE Claim_id__c = :c.Claim_Id__c). Short of using a query, I don't see any specific way to reliably determine the error just from the getMessage() function.
All Answers
You could call getDmlFields to determine the fields which failed. From there, you could construct a query to find the duplicated value (SELECT Id FROM Case WHERE Claim_id__c = :c.Claim_Id__c). Short of using a query, I don't see any specific way to reliably determine the error just from the getMessage() function.
I would just interpret the string... You know the object prefix id, so you can just do a string match against '500' and grab the 18 characters.
If you need the name of the record as well: then you need to do a query.
Hey thank you guys,
I did what sfdcfox suggested, a query where the duplicated value exists in database.
I was wondering if multiple concurrent requests to this service would generate problems when querying a record that its still being inserted on database. But looks like salesforce is doing its job about concurrency.
I will keep monitoring the service!
thanks!
In practice, this probably shouldn't matter, but in theory, a long-running transaction might cause a "UNABLE_TO_LOCK_ROW" error on the second transaction. The user that receives the error would just have to try to submit again.