[12.x] :feat: Add Job Failure Callbacks to Batch
Functional Enhancement
The functional change is in PendingBatch::allowFailures(), which now accepts:
- A boolean value (original behavior)
- A callable/Closure
- An array of callables/Closures
This allows the registration of callbacks that will be executed when a job fails, providing more granular control over failure handling in batch processing. The Batch class has been updated with corresponding methods to handle these new failure callbacks.
// New usage example:
$batch->allowFailures(function ($batch, $exception) {
// Handle individual job failure
Log::error("Job failed in batch {$batch->id}: {$exception->getMessage()}");
});
Of course, $batch->allowFailures() and $batch->allowFailures($boolean) still work as before.
Additional Changes
- Refactored callback invocation into a centralized
invokeCallbacksmethod in the Batch class
Notes
- I debated going with
$batch->failure($callback)instead of dual-purposing$batch->allowFailures(), but went with the latter since the former would require either a call toallowFailures()anyway, setting this option implicitly in thefailure()implementation, or reworking the logic ofallowsFailures()to also return true when failure callbacks are present. I'm open to reworking this in any of those directions. - I'll add tests once the prior question is resolved.
- I envision a possible future
JobContextobject that would be passed to the callback providing more job specific detail, making this potentially more useful.
Hey @coderabbi - is it possible to remove the formatting changes... just makes the diff easier for me to review quickly.
On it!
Done!
@coderabbi so is this similar to catch, but it is invoked for every job failure, not just the first one?
@taylorotwell
Exactly.
As I noted in the description, probably more useful when paired with a JobContext passed to the callback with additional job-specific details, but... babysteps (though if you're inclined to accept this, can certainly incorporate that here).
@coderabbi so is this similar to
catch, but it is invoked for every job failure, not just the first one?
It's like catch(), except that it continues, and also progress(), except that it fires on failure rather than success.
@taylorotwell would love to add tests to this if there's a general inclination towards approval.
@yitzwillroth yeah I think fine to add tests here.
Would it make sense to also have a mechanism to only invoke on errors when the batch is completed?
@taylorotwell Tests added as requested.
Thanks!