+ Start a Discussion
TekoptimizeTekoptimize 

how to handle the list of exception messgaes while inserting records

Hi All,
 
   I'm facing the problem from exception message.Actually,my requirement is i need to insert the list of records.while inserting if any exceptions for each record, i need to get all the error messages with record id.please help to me , how can i handle this error messgaes for each record.

Thanks to All....

mbhardwajmbhardwaj

This example shows how to get the errors returned by aDatabase.insertoperation. It inserts two accounts, one of which doesn’t have the required Name field, and sets the second parameter tofalse:Database.insert(accts, false);. This sets the partial processing option. Next, the example checks if the call had any failures throughif (!sr.isSuccess())and then iterates through the errors, writing error information to the debug log.

 
// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) { if (!sr.isSuccess()) { // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug('Fields that affected this error: ' + err.getFields()); } } }
TekoptimizeTekoptimize
Hi mbhardwaj ,

Thanks for reply..I done what you are showed in reply.but i'm not able to
get the error messages? how can i get the error messages through mail.plz
tell me solution.
mbhardwajmbhardwaj

Try this code::::

 

// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account()};
Database.SaveResult[] srList = Database.insert(accts, false);
String emailBody = 'The following error has occurred.';

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (!sr.isSuccess()) {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            emailBody = emailBody + sr.getId() + ':' + err.getStatusCode() + ': ' + err.getMessage() +'<br/>';
        }
    }
}
//Send EMail
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'user@acme.com'};
mail.setToAddresses(toAddresses);
mail.setReplyTo('support@acme.com');
mail.setSubject('Errors in Insert Process');
mail.setHtmlBody(emailBody);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });