If you want to handle all failing commands, then go for Failed job events like Petay suggested.
If you want to handle failure for a single job, you can implement the failed
method, just like you implemented the handle
method.
You may define a failed method directly on your job class, allowing you to perform job specific clean-up when a failure occurs. This is the perfect location to send an alert to your users or revert any actions performed by the job. The Exception that caused the job to fail will be passed to the failed method:
class ProcessPodcast implements ShouldQueue
{
use InteractsWithQueue, Queueable, SerializesModels;
public function handle()
{
// Handle job and throw exception
}
public function failed(Exception $exception)
{
// Create log file
}
}
Marking a job as failed can be done using the --tries
option when calling the worker.
Then, when running your queue worker, you should specify the maximum number of times a job should be attempted using the --tries switch on the queue:work command. If you do not specify a value for the --tries option, jobs will be attempted indefinitely:
php artisan queue:work redis --tries=3
In case you want to trigger a failure manually you can either throw an exception or return the statuscode like so:
public function handle(): int
{
if($somethingWentWrong) {
return -2;
}
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…