5

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');
accts.add(a);
}
Account accountToUpdate;
try
{
   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?

2
  • 1
    Do you have to do this through code? i.e. is this for test coverage? Or would you be better to use the Data loader?
    – Nick C
    Commented Jul 7, 2014 at 5:39
  • Its not a requirement. Just curious about how to achieve this through apex.
    – MnZ
    Commented Jul 7, 2014 at 5:47

2 Answers 2

5

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';
contacts.add(contact1);

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

// 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 
    }
    else
    {
        // Failed
        for(Database.Error error : saveResult.getErrors())
        {
            System.debug('Something went wrong with the record ID ' + saveResult.getId() + ' : ' + error.getStatusCode() + ' - ' + error.getMessage());
        }
    }
}
1
  • Sorry for the late acceptance. A cue from a fellow stackexchange user. Thanks #rao
    – MnZ
    Commented Oct 22, 2014 at 18:29
0

I tried with same code in case of failure but saveResult.getId() is null. we need the ids of the failure records.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database_saveresult.htm#apex_Database_SaveResult_getId

Salesforce says if it not success then saveResult.getId() will be blank.

Any idea how to capture the failure records ID?

You must log in to answer this question.

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