0

I'm trying to upsert some records. I use Database.upsert. If the failure is related to a duplicate value (external ids that have to be unique) I need to know what fields are duplicate and clear (sanitize in the code) them to try to upsert again.

  Database.UpsertResult result = firstResults.get(i);
  if (!result.isSuccess()) {
     SObject original = originals.get(i);
     sanitized.put(i, sanitize(original, result));
  }

The sanitize method is this:

private SObject sanitize(SObject original, Database.UpsertResult upsertResult) {
  SObject clone = original.clone(false, true, false, false);
  for (Database.Error error : upsertResult.getErrors()) { // this is line 66
    if (error.getStatusCode() == System.StatusCode.DUPLICATE_VALUE) {
      clear(clone, error.getFields());
    }
  }
  return clone;
}

The clearing doesn't work. Checking the log, I see this message:

|VARIABLE_ASSIGNMENT|[66]|error|"Error [statusCode=DUPLICATE_VALUE, code=[xmlrpc=1272, statusCode=DUPLICATE_VALUE, exceptionCode=DUPLICATE_VALUE, scope=PublicApi, http=400], message=duplicate value found: \u003Cunknown\u003E duplicates value on record with id: \u003Cunknown\u003E, fields=null]"

Please note it contains fields=null. So the code is not clearing any fields.

How can I know what fields are duplicate? Why is the fields member of the error not populated?

1 Answer 1

0

You can use exception handling. To catch use DMLException and it's method getDmlFieldNames to track the field name that caused the error.

try{
    upsert sobject;
}
catch(Exception e){
    System.debug(e.getDmlFieldNames()); // This will return list of fields due to which error occurred
}

You must log in to answer this question.

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