Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question
    
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 Cook Jul 7 at 5:39
    
Its not a requirement. Just curious about how to achieve this through apex. –  MnZ Jul 7 at 5:47

1 Answer 1

up vote 5 down vote accepted

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());
        }
    }
}
share|improve this answer
    
Sorry for the late acceptance. A cue from a fellow stackexchange user. Thanks #rao –  MnZ 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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