Use BatchApexErrorEvent Triggers to Monitor ISV Applications With Example (Salesforce Spring ’21 Release)

Include BatchApexErrorEvent triggers in your managed package to monitor the health of batch jobs and take necessary corrective action without any post-installation steps.

Where: This change applies to Lightning Experience and Salesforce Classic.

How: The BatchApexErrorEvent object represents a platform event associated with a failing batch Apex execution. To fire this platform event, a batch Apex class declaration must implement the Database.RaisesPlatformEvents interface. A BatchApexErrorEvent platform event is fired when a batch Apex job encounters an unhandled exception. For more details, see Firing Platform Events from Batch Apex in the Apex Developer Guide.

The BatchApexErrorEvent object represents a platform event associated with a batch Apex class. This object is available in API version 44.0 and later. If the startexecute, or finish method of a batch Apex job encounters an unhandled exception, a BatchApexErrorEvent platform event is fired. For more details, see BatchApexErrorEvent.

To fire a platform event, a batch Apex class declaration must implement the Database.RaisesPlatformEvents interface.

  1. public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>,
  2. Database.RaisesPlatformEvents{
  3. // class implementation
  4. }

Example

This example creates a trigger to determine which accounts failed in the batch transaction. Custom field Dirty__c indicates that the account was one of a failing batch and ExceptionType__c indicates the exception that was encountered. JobScope and ExceptionType are fields in the BatchApexErrorEvent object.

  1. trigger MarkDirtyIfFail on BatchApexErrorEvent (after insert) {
  2. Set<Id> asyncApexJobIds = new Set<Id>();
  3. for(BatchApexErrorEvent evt:Trigger.new){
  4. asyncApexJobIds.add(evt.AsyncApexJobId);
  5. }
  6. Map<Id,AsyncApexJob> jobs = new Map<Id,AsyncApexJob>(
  7. [SELECT id, ApexClass.Name FROM AsyncApexJob WHERE Id IN :asyncApexJobIds]
  8. );
  9. List<Account> records = new List<Account>();
  10. for(BatchApexErrorEvent evt:Trigger.new){
  11. //only handle events for the job(s) we care about
  12. if(jobs.get(evt.AsyncApexJobId).ApexClass.Name == 'AccountUpdaterJob'){
  13. for (String item : evt.JobScope.split(',')) {
  14. Account a = new Account(
  15. Id = (Id)item,
  16. ExceptionType__c = evt.ExceptionType,
  17. Dirty__c = true
  18. );
  19. records.add(a);
  20. }
  21. }
  22. }
  23. update records;
  24. }

Comments

Post a Comment

Popular posts from this blog

Adding a red asterisk to required fields using label in LWC

The Developer Console didn't set the DEVELOPER_LOG trace flag on your user. Having an active trace flag triggers debug logging. You have 1,978 MB of the maximum 1,000 MB of debug logs. Before you can edit trace flags, delete some debug logs.

Salesforce: Serial and Parallel Approval