Notifications
Clear all
Sep 07, 2021 4:44 am
How to get a list of ids or any other field for those failed records in a bulk dml operation?
1 Reply
Sep 07, 2021 5:19 am
// This is one way. This won't give you id's or any other fields, but just the field that caused the exception: List srList = Database.insert(recsToInsert, false); for (Database.SaveResult sr : srList) { if (sr.isSuccess()) { // Operation was successful, get the ID of the record that was processed System.debug('Successfully inserted. ID: ' + sr.getId()); } else { // Operation failed, 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()); } } } // Another method. This will give you the id's or any other field you need: List srList = Database.insert(recsToInsert, false); for(Integer i=0;i<srList.size();i++){ if (srList.get(i).isSuccess()){ srList.get(i).getId(); }else if (!srList.get(i).isSuccess()){ // DML operation failed Database.Error error = srList.get(i).getErrors().get(0); String failedDML = error.getMessage(); recsToInsert.get(i);//failed record from the list system.debug('Failed Id: '+recsToInsert.get(i).Your_field__c); } } // Also check out - handle errors in salesforce batch apex: https://www.forcetalks.com/salesforce-topic/how-to-handle-error-records-in-salesforce-batch-apex/