Capture the data from database.saveresult

Scenario

Create three account records, one with missing required information. Once the code is executed then the two records are saved to the database. The one record which is not saved should print error

Code Snippet

Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account(),
    new Account(Name='Account3')    
        };
   Database.SaveResult[] sr = Database.insert(accts, false);


       for (Database.SaveResult sr : sr) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('Successfully inserted account. Account ID: ' + sr.getId());
            }
           
    else {
        for(Database.Error err : sr.getErrors()) {
            system.debug('err'+err);
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
  }

Understanding code line by line

Create three records

Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account(),
    new Account(Name='Account3')    
        };

Database.SaveResult[]

An array of SaveResult objects contains the result of insert or update DML operation returned by a Database method. Each element in the SaveResult array corresponds to the sObject array passed as the sObject[] parameter in the Database method.

Database.insert()

If we use Insert then the partial insert and rollback is not supported. If an error occurs the execution will stop and none of the records will insert into the database. For partial insertion and rollback we use Database.Insert. Database methods are static methods available in Database class. If an error occurs the remaining records will be inserted/updated means partial DML operation will be done. The only record throwing an error will not be inserted/updated.

In this use case, Account 1 and Account 3 are saved to database and second record is not saved to database as I have used Database.Insert(accts, false) supporting partial transaction.

Database.SaveResult[] srList = Database.insert(accts, false);

Debug Log to see record stored in SaveResult[]

//1st record
(Database.SaveResult[getErrors=();
getId=0010b00002LYu80AAD;isSuccess=true;], 

//2nd record 
Database.SaveResult[getErrors=(Database.Error[getFields=(Name);
getMessage=Required fields are missing: [Name];
getStatusCode=REQUIRED_FIELD_MISSING;]);getId=null;isSuccess=false;],

//3rd record
Database.SaveResult[getErrors=();getId=0010b00002LYu81AAD;isSuccess=true;])

Iterate over saveresult

for (Database.SaveResult sr : srList) {}

isSuccess:

It is a method in SaveResult. It returns a Boolean that is set to true if the DML operation was successful for this object, false otherwise.

 if (sr.isSuccess()) {}

Database.error:

Represents information about an error that occurred during a DML operation when using a Database method.

Error class is part of SaveResult, which is generated when a user attempts to save a Salesforce record.

for(Database.Error err : sr.getErrors()) {}

getFields()

Returns an array of one or more field names which have the error condition.

System.debug('Account fields that affected this error: ' + err.getFields());

Result

getFields=(Name);

getMessage() : Returns the error message text.

System.debug(err.getMessage());

Result

getMessage=Required fields are missing: [Name];

getStatusCode():

Returns a code that characterizes the error.

System.debug(err.getStatusCode());

Result

getStatusCode=REQUIRED_FIELD_MISSING

For more of these kind of articles stay tuned.Happy coding !

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes