5

When long-running batches fail I want the starting user to be notified in the org using Custom Notifications.

Therefore I added the marker-interface Database.RaisesPlatformEvents to the Batch class

public with sharing class MyBatch implements Database.Batchable<SObject>, Database.AllowsCallouts, Database.Stateful, Database.RaisesPlatformEvents {
   ...
}

created a trigger

trigger BatchApexErrorEvents on BatchApexErrorEvent (after insert) {
    new HandleBatchErrors(Trigger.new).execute();
}

which delegates to

public with sharing class HandleBatchErrors {

   ...

    public void execute() {
        for(BatchApexErrorEvent event : events) {
            Messaging.CustomNotification notification = new Messaging.CustomNotification();
            notification.setNotificationTypeId(typeID);
            notification.setTitle('title');
            notification.setTargetId('000000000000000AAA');
            ...
            notification.send(userId)
        }
    }
}

But no notifications show up. I see the errors in the Apex Job Logs but that's all.

  • implying that Automated Process user is not permitted to send Custom Notifications? – cropredy Oct 13 at 22:14
  • I don’t get you... – Robert Sösemann Oct 13 at 22:30
  • 3
    the trigger runs in user context = Automated Process user; Winter 21 requires user to have specific permission: help.salesforce.com/…; is it possible that Automated Process user doesn't have this permission? – cropredy Oct 14 at 0:14
  • Whats the value of userId? The autoproc user the event trigger runs as? Or the user that the batch job was running as? – ca_peterson Oct 15 at 6:37
  • The user that kicked of the batch @ca_peterson – Robert Sösemann Oct 15 at 6:56
2

The hint given by Chris Peterson in the comment helped me solve it. It was the userId used in

notification.send(userId);

It was set to UserInfo.getUserId() which in the context of the BatchApexErrorEvent trigger was an Automated Process. When I changed it to the user that kicked of the Batch by querying

[SELECT CreatedById FROM AsyncApexJob WHERE Id event.AsyncApexJobId]

notification.send(job.CreatedById);

everything worked out just fine.

| improve this answer | |
  • Woohoo! glad it helped. I was just starting to hunt down who owns this in case it didn't. – ca_peterson Oct 15 at 20:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.