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
Scott McArthur 8Scott McArthur 8 

alerts for failing batch Apex job

I have a batch Apex job that was failing however I did not get any error emails even though I have got myself set up to receive 'Apex Exception Email'  Any ideas on how to set up proper alerting for this or why this did not work? 
pranoti patilpranoti patil
Hi,

Write the below code inside a finish method of apex batch job to get the job failure email.

public void finish(Database.BatchableContext BContext){
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
                        TotalJobItems, CreatedBy.Email
                        FROM AsyncApexJob WHERE Id =
                        :BContext.getJobId()];
        if(a.NumberOfErrors >=1){                
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'abc@gmail.com'});
        mail.setSubject('job '+a.Status);
        mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
        ' batches with '+ a.NumberOfErrors + ' failures.');
        
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }

Kindly mark it is as an answer if this resolves your query.