如何为作业批次 Laravel 8 中的每个失败作业调用`catch` 闭包

问题描述

Laravel 8 引入了作业批处理,它允许批量执行作业并在批处理完成和失败时执行操作。当批处理中的作业失败时,将执行 catch 回调并将整个批处理标记为“已取消”according to the documentation。如果您不希望批次取消(在第一次失败时),您可以在分派批次时附加方法 allowFailures()

$batch = Bus::batch([
    // ...
])->then(function (Batch $batch) {
    // All jobs completed successfully...
})->catch(function (Batch $batch,Throwable $e) {
    // First batch job failure detected...
    
    // Todo: call this for every Failed job

})->allowFailures()->dispatch();

它按预期工作,但是我想知道是否可以为每个失败的作业调用 catch 闭包? (在这种情况下使用 allowFailures

解决方法

您可以使用 Jobs 中的尝试次数来查找失败的作业

  if ($this->attempts() > 1) {
  // your code
  }