[SalesForce] How to capture those records that was unable to get inserted

Say, I have a list of 1000 records to be inserted. How to capture those records that failed to get inserted? I realize that I can use DMLException to get the error. But how to get a list of failed insertions. Here's a situation I created to demonstrate my requirement.

Account[] accts = new List<Account>();
for(Integer i=0;i<1000;i++) {
Account a = new Account(Name='Acme' + i, BillingCity='San Francisco');
Account accountToUpdate;
   insert accts;        
catch(DmlException e) 
 System.debug('An unexpected error has occurred: ' + e.getMessage());

Say record Acme50 and Acme62 didn't get inserted. How to get a list of failed records?

Best Answer

You need to use Database.insert() method and get results by using Database.SaveResult.

Also, have a look at the DML parameter optAllOrNone documented here. if you want to roll back the operation in case 1 record fails.

Example code:

List <Contact> contacts = new List <Contact> ();

Contact contact1 = new Contact();
contact1.FirstName = 'TestFirstname';
contact1.LastName = 'TestSurname';

Contact contact2 = new Contact();
contact2.FirstName = 'TestFirstname';

// Assuming contact2 will fail not having last name populated
List <Database.SaveResult> saveResults = Database.insert(contacts, false);

// Go through each result
for (Database.SaveResult saveResult : saveResults)
    if (saveResult.isSuccess() == true)
        // Successfully inserted contact
        // do something 
        // Failed
        for(Database.Error error : saveResult.getErrors())
            System.debug('Something went wrong with the record ID ' + saveResult.getId() + ' : ' + error.getStatusCode() + ' - ' + error.getMessage());
Related Topic