1

I have below method and error is coming beacuse of some validation/trigger is on account and need to catch the exception If i am runnning this from Ui for one record this will throw an exception as i am using[0],

but what in case i am using data load and inserting/updating 5 records and if the exception is for 3rd record,still it will throw for first record only. Please suggest how to handle this

public static void updatecon(list<account>conlist){

      for (contact con: conlist){
           Ids.put(con.accountId, con.Id);
      } 


      for(Account acc: [Select Id, vlocity_cmt__PersonContactId__c, Type from Account where Id In:Ids.keyset()]){      
                Account acnt = new Account();
                acnt.Id = acc.Id;
                acnt.status  = 'Inactive';
                AccList.add(acnt);
        }

    if(AccList.size()>0){  
        try{     
            update AccList;
        }
        catch(dmlexception e){
            conlist[0].adderror(e.getMessage()); 
        }

    }   
}

1 Answer 1

2

For this I suggest you to use Database class, using that you first get the error message and then append it to the record.

Database.SaveResult[] srList = Database.insert(AccList, false);
Integer count = 0;
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (!sr.isSuccess()) {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Fields that affected this error: ' + err.getFields());

            AccList[count ].adderror(err.getMessage()); 
        }
    }
     count ++;
}
3
  • The usual way to handle this is only to handle the first error in the list; addError can only show one error per record and one error per unique field, so there's really no reason to iterate all the errors unless you're going to join them together into one really big string.
    – sfdcfox
    Commented Dec 13, 2018 at 13:27
  • is there any way then throw an error on perticular record
    – sudhanshu
    Commented Dec 14, 2018 at 4:20
  • @sam this approach will work. Did you tried it and face any challenge? Commented Dec 14, 2018 at 5:15

You must log in to answer this question.

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