implements Database.RaisesPlatformEvents を使ったら、バッチ実行が失敗した時、操作ができる
BatchApexErrorEventというオブジェクトにトリガーを入れる
この例では、一括処理トランザクションで失敗したアカウントを判断するトリガを作成します。カスタム項目 Dirty__c は、アカウントが失敗した一括処理のいずれかであったことを示し、ExceptionType__c は発生した例外を示します。JobScope と ExceptionType は、BatchApexErrorEvent オブジェクトの項目です。
trigger MarkDirtyIfFail on BatchApexErrorEvent (after insert) {
Set<Id> asyncApexJobIds = new Set<Id>();
for(BatchApexErrorEvent evt:Trigger.new){
asyncApexJobIds.add(evt.AsyncApexJobId);
}
Map<Id,AsyncApexJob> jobs = new Map<Id,AsyncApexJob>(
[SELECT id, ApexClass.Name FROM AsyncApexJob WHERE Id IN :asyncApexJobIds]
);
List<Account> records = new List<Account>();
for(BatchApexErrorEvent evt:Trigger.new){
//only handle events for the job(s) we care about
if(jobs.get(evt.AsyncApexJobId).ApexClass.Name == 'AccountUpdaterJob'){
for (String item : evt.JobScope.split(',')) {
Account a = new Account(
Id = (Id)item,
ExceptionType__c = evt.ExceptionType,
Dirty__c = true
);
records.add(a);
}
}
}
update records;
}