I have a batch class which performs certain DML operation in execute method based on certain conditions. Also performing an update under finish method. I have a constructor where parameters of type string and date are passed.
We are scheduling this batch class for one requirement A and it is working fine. Now we have a new requirement B and its similar to requirement A, so we are using the same batch class but passing different parameters to the constructor based on the requirement. Now we need to send email to admin/group whenever this batch job fails for both requirements. So we used Database.RaisesPlatformEvents interface which fires BatchApexErrorEvent when batch class fails. We used a platform event triggered flow to subscribe BatchApexErrorEvent and then fire an email from flow.
Problem Statement: The problem here is since we are using same batch class for both requirements A and B we are unable to find or differentiate for which requirement the batch class has failed. Is there any solution to find for which parameter the batch class has failed so that we can differentiate and send failure emails accordingly.
Example of the Batch class:
public class SearchAndReplace implements Database.Batchable<sObject>{
private String Query;
private Date Entity;
public SearchAndReplace(String q, Date e){
Query=q; Entity=e;
}
public Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
public void execute(Database.BatchableContext BC, List<sObject> scope){
for(sobject s : scope){
//conditions and operations
}
//performing DML operations
}
public void finish(Database.BatchableContext BC){
//update statement
}
}
Using the batch class for Requirement A: Date dateInstance = date.newInstance(2022,07,28); SearchAndReplace batchInstance = null; batchInstance = new batchInstance ('Account',dateInstance ); Id jobid = Database.executeBatch(batchInstance,200);
Using the batch class for Requirement B: Date dateInstance = date.newInstance(2022,07,28); SearchAndReplace batchInstance = null; batchInstance = new batchInstance ('Contact',dateInstance ); Id jobid = Database.executeBatch(batchInstance,200);
JobScope
and determine the SObject type by examining the first ID: there are means to take anId
and get theSObjectType
from it.