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
JA-DevJA-Dev 

Handling exception during a partial save

Hi,

 

We have a batch job that updates a number of records and it could potentially throw a DML exception. I was trying to capture the ids of the records that caused an exception, but it seems that it won't return the ids. Here is a snippet of what it looks like:

 

 

Database.SaveResult[] lsr = Database.update(recordsToUpdate, false);
for (Database.SaveResult sr : lsr) {
    if (sr.isSuccess()) {
        // This gets me the ids as expected
        successRecords = successRecords + sr.getId() + ',';
    else if (!sr.isSuccess()) {
        // This does not capture the ids of the failed records
        errorRecords = errorRecords + sr.getId() + ',';
    }
}

 

Also, I saw that there is an Database.SaveResult.getErrors() function that I have not tried using yet. Would that give me the id of the failed record? I'm simply trying to capture any records that did not update, so that we can later reprocess.

 

Thanks in advance!

 

 

forecast_is_cloudyforecast_is_cloudy

Per the Apex documentation for the 'getId' method:

 

"The ID of the sObject you were trying to insert or update. If this field contains a value, the object was successfully inserted or updated. If this field is empty, the operation was not successful for that object."
So basically, if your update failed, the getId() method will not return a value. In order to identify the id of the failed record, you can do something like this:
Database.SaveResult[] lsr = Database.update(recordsToUpdate, false);
Integer i = 0;
for (Database.SaveResult sr : lsr) {

    if (sr.isSuccess()) {
        // This gets me the ids as expected
        successRecords = successRecords + sr.getId() + ',';
    else if (!sr.isSuccess()) {
        // This does not capture the ids of the failed records
        errorRecords = errorRecords + recordsToUpdate[i].id + ',';
    }
    i++;
}