I would like to insert list of records, catch various exceptions, and if the exception is something I can't handle send the offending objects for manual processing.
I can write most of what I need, but one thing has me stumped, the return information in the SaveResult class after a Database.Insert.
There is a similar question with an accepted answer, however the ID is null so there is not a way to access the object that failed to be inserted. How to capture those records that was unable to get inserted?
From the documentation on SaveResult and Exception handling:
SF shows:
Database.insert(contacts, false);
Which returns the SaveResult. However the only methods available in the SR are:
- getErrors()
- getId()
- isSuccess()
None of these help on determining the records that fail on an insert. getErrors provides additional error reporting about the exact error, getId only works on updates, isSuccess is a boolean.
The code below demonstrates my issue:
Account a = new Account(Name = '');
Database.SaveResult SR = Database.insert(a, False);
System.debug('SaveResult: ' + SR);
Debug:
DEBUG|SaveResult: Database.SaveResult[getErrors=(Database.Error[getFields=(Name);getMessage=Required fields are missing: [Name];getStatusCode=REQUIRED_FIELD_MISSING;]);getId=null;isSuccess=false;]
Is there a way to access the failed records on an insert? One thought I had was if there is a failure loop though the original list and weed out the ones that have an ID and handle the exceptions that way. But I think that would get tedious with loop after loops as I try to handle the exceptions and continue to have failures.
UPDATE: As a proof of concept for the above
List<Account> accs = new List<Account>();
Account a = new Account(Name = 'TestingAccOne');
Account b = new Account(Name = '');
accs.add(a);
accs.add(b);
Database.SaveResult[] SR = Database.insert(accs, False);
System.debug('SaveResult: ' + SR);
System.debug('accs: ' + accs);
Debug: SR:
USER_DEBUG [7]|DEBUG|SaveResult: (Database.SaveResult[getErrors=();getId=001R000000sLHNhIAO;isSuccess=true;], Database.SaveResult[getErrors=(Database.Error[getFields=(Name);getMessage=Required fields are missing: [Name];getStatusCode=REQUIRED_FIELD_MISSING;]);getId=null;isSuccess=false;])
List:
USER_DEBUG [8]|DEBUG|accs: (Account:{Name=TestingAccOne, Id=001R000000sLHNhIAO}, Account:{Name=})
From the above I'm leaning toward removing all records from the above list with an ID and then can focus on the offending ones.
Any suggestions and input are greatly appreciated.