Apex 一括処理からのプラットフォームイベントの起動
イベントメッセージでは、Apex ジョブ UI よりも詳細なエラーの追跡情報が提供されます。イベントレコードには処理中のレコード ID、例外種別、例外メッセージ、スタック追跡が含まれます。失敗のカスタム処理と再試行ロジックを組み込むこともできます。カスタム Apex ロジックは、この種のイベントの任意のトリガーから呼び出すことができるため、Apex 開発者はカスタムロギングや自動再試行処理などの機能を構築できます。
プラットフォームイベントの登録については、「プラットフォームイベントの登録」を参照してください。
BatchApexErrorEvent オブジェクトは、Apex 一括処理クラスに関連付けられているプラットフォームイベントを表します。このオブジェクトは API バージョン 44.0 以降で使用できます。Apex の一括処理ジョブの start、execute、または finish メソッドで未対応の例外が発生すると、BatchApexErrorEvent プラットフォームイベントが発生します。詳細は、『プラットフォームイベント開発者ガイド』の「BatchApexErrorEvent」を参照してください。
1public with sharing class YourSampleBatchJob implements Database.Batchable<SObject>,
2 Database.RaisesPlatformEvents{
3 // class implementation
4}例
1trigger 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
7 Map<Id,AsyncApexJob> jobs = new Map<Id,AsyncApexJob>(
8 [SELECT id, ApexClass.Name FROM AsyncApexJob WHERE Id IN :asyncApexJobIds]
9 );
10
11 List<Account> records = new List<Account>();
12 for(BatchApexErrorEvent evt:Trigger.new){
13 //only handle events for the job(s) we care about
14 if(jobs.get(evt.AsyncApexJobId).ApexClass.Name == 'AccountUpdaterJob'){
15 for (String item : evt.JobScope.split(',')) {
16 Account a = new Account(
17 Id = (Id)item,
18 ExceptionType__c = evt.ExceptionType,
19 Dirty__c = true
20 );
21 records.add(a);
22 }
23 }
24 }
25 update records;
26}Apex 一括処理ジョブから発行される BatchApexErrorEvent メッセージのテスト
失敗した Apex 一括処理ジョブによって発行されるイベントメッセージを配信するには、Test.getEventBus().deliver() メソッドを使用します。一括処理ジョブを実行するには、Test.startTest() および Test.stopTest() ステートメントブロックを使用します。
このスニペットは、Apex の一括処理ジョブを実行し、イベントメッセージを配信する方法を示しています。これは Test.stopTest() の後で一括処理ジョブを実行します。この一括処理ジョブは、Database.RaisesPlatformEvents の実装により、失敗が発生すると BatchApexErrorEvent メッセージを公開します。Test.stopTest() が実行された後に、別の Test.getEventBus().deliver() ステートメントが追加され、BatchApexErrorEvent を配信できるようになります。
1try {
2 Test.startTest();
3 Database.executeBatch(new SampleBatchApex());
4 Test.stopTest();
5 // Batch Apex job executes here
6} catch(Exception e) {
7 // Catch any exceptions thrown in the batch job
8}
9
10// The batch job fires BatchApexErrorEvent if it fails, so deliver the event.
11Test.getEventBus().deliver();