function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BroncoBoyBroncoBoy 

Handling Errors When Inserting/Updating a <List> of Objects/Records

Scenario:
In this example (not a batch process) I have a list of 100 contact records:  List <Contact> contactsToUpdate = new List <Contact> ();
// contactsToUpdate.size() = 100

I loop through these using a for loop,  I update a few records. Then I upsert them using DML.  Result:  a few records have been updated and a few are new & are inserted.  
if (contactsToUpdate.size() > 0) 
        {
            try 
            {
                upsert contactsToUpdate;
            } 
            catch(DmlException e) 
            {
                system.debug('The following exception has occurred: ' + e.getMessage());
            } 
        }

Here are my questions:

1)  If only 1 of those 100 records cannot be inserted do to something like a validation rule failing, will the entire insert fail or just the one record?
2)  Is there a way in the Catch that I could email myself only the records that fail and the reason - can I use the database.upsert in a try catch?
 

Thank you!
Brandon

Best Answer chosen by BroncoBoy
Balaji BondarBalaji Bondar
Hi BroncoBoy,
1. By using the above code if one record will fail all the records will fail.To acheive this you have to use:
UpsertResult Database.Upsert(sObject recordToUpsert, Schema.SObjectField External_ID_Field, Boolean opt_allOrNone)
http://www.salesforce.com/us/developer/docs/dbcom_apex250/Content/apex_dml_upsert.htm

In catch block you have to code to receive the records which are failing .You can access records using upserResult.

Important :
If this is what you were looking for then please mark it as a "SOLUTION" or You can Click on the "Like" Button if this was beneficial for you.