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
Abhishek Pal 33Abhishek Pal 33 

How to show the failed records in batch on VF page?

Hello everyone,

I am using a VF page where user click on Execute Button then the Batch will execute. Now I am using Database.upsert(scope,false) which means if the record failed then the complete batch will not fail only the records which have error failed?

How can we show to the users which records are failed on VF page?

NOTE: What have read in the docs that you can't pass value from batch apex to controller.

Thanks in advance.

-Abhishek
SonamSonam (Salesforce Developers) 
Hi Abhishek,

Since batch apex executes in async mode, you cannot show them on the same page.

There are multiple ways you can display that:

- Once the records are failed, you can get the user id who initiated the batch and send an email with failed records to that User.
- You can create an Exception / Error object and insert the failed records in that object.

Sample working code:

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); // Set recipients to two contact IDs. // Replace IDs with valid record IDs in your org.
message.toAddresses = new String[] { '003D000000QDexS', '003D000000QDfW5' };
message.optOutPolicy = 'FILTER'; message.subject = 'Opt Out Test Message';
message.plainTextBody = 'This is the message body.'; Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message}; Messaging.SendEmailResult[] results = Messaging.sendEmail(messages); if (results[0].success)
{ System.debug('The email was sent successfully.'); }
else
{ System.debug('The email failed to send: ' + results[0].errors[0].message); }