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()); 
        }

    }   
}
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 ++;
}
  • 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 Dec 13 '18 at 13:27
  • is there any way then throw an error on perticular record – sudhanshu Dec 14 '18 at 4:20
  • @sam this approach will work. Did you tried it and face any challenge? – Tushar Sharma Dec 14 '18 at 5:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.