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

Want to get error when a Batch job failed.

Hi Experts,
I have a requirement to send email to a recient when a batch job gets failed. I want to test it from Developer console. Please help.

Keyur  ModiKeyur Modi
Try with below 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);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    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 {
       // send mail 

for more clarification on this go through below link.

Keyur Modi
Amit Chaudhary 8Amit Chaudhary 8
Example 1:-
global void execute(Database.batchablecontext bc) {

    // Check batch status - IF COMPLETED then 
    AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
        TotalJobItems, CreatedBy.Email, ExtendedStatus
        from AsyncApexJob where Status == 'Failed'];        

    if(a.Status == 'Failed') {

        // 1. Send Email (CSV created in execute method)

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        // Send the email to the job submitter
        String[] toAddresses = new String[] {a.CreatedBy.Email};
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('x70RecordExtract  Status: ' + a.Status);
            mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
            ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);

        // Add your attachment to the email.

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

        // 2. database.executebatch(new chain_batch(),200);


Exmaple 2:- 
global class TestBatch implements Database.Batchable<sObject>, Database.Stateful {

    global List<Log__c> logs;

    global TestBatch() {
        logs = new List<Log__c>();

    global Database.QueryLocator start(Database.BatchableContext BC) {
        query = 'Your query...';
        return Database.getQueryLocator(query);

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        for (sobject s : scope) {
                Your logic goes here...
            } catch (Exception e) {
                logs.add(new Log__c(
                        Name__c = '...',
                        Stacktrace__c = e.getStackTraceString()
                throw e;
        update scope;

    global void finish(Database.BatchableContext BC) {
        insert logs;

Please let us know if this will help you

Amit Chaudhary
Nitish KumarNitish Kumar
You can go through this article to send emails when your batch class is failing.