Get record field after Error in Database.Upsert

apexdatabasedml

I'm upserting some records using Database.upsert, after that, I'm supposed to get the errors and pass them to a custom logger.

The problem is, the way this class works, I'd need to get a field value from the object that failed to upsert, is there any way to do so?

As far as I know, resultUpsert.getErrors won't return me any of the upserted fields.

Here's a code snippet of what I'm trying to do, it's not really doing anything, but anyway:

   if(lstNota.size() > 0){
            List<Database.upsertResult> resultUpsert = Database.upsert(lstNota, Nota_Fiscal__c.ID_externo_JDE__c, false);
            
            for(Integer i = 0; i < resultUpsert.size(); i++){
                ResponseNota res = new ResponseNota();
                if(!resultUpsert[i].isSuccess()){
                    if(resultUpsert.isCreated){

                    } else {
                       // here I'd like to access the fields to pass to my logger class, if possible.                       
                    }
                }
            }          
        }

I'm fine with any approaches to this, as long as it gets done.

Best Answer

The array of List<Database.upsertResult> will be in the same order as the records in lstNota. In other words:

for(Integer i = 0; i < resultUpsert.size(); i++){
  ResponseNota res = new ResponseNota();
  if(!resultUpsert[i].isSuccess()){
    if(resultUpsert[i].isCreated){
      // ...
    } else {
      sObject record = lstNota[i];
      doSomethingWith(record, resultUpsert[i]);
    }
  }
}
Related Topic