Laravel: Can I fail 'well' in an handle() of a Job?

霸气de小男生 提交于 2019-12-11 14:42:36

问题


I know that, if a job throw an Exception, the job fails, and will be retried automatically from queue worker in a few seconds.

My question is: can i fail in a controlled way?

I'd like to catch exceptions, create a more smal log, and, for example, return false to mark job as failed.

Is there a way?

Precisation: I DO NOT want to HANDLE failure. I want to provocate a failure without throwing exceptions. I some edge cases I need that jobs fails. But I also need to avoid to throw Exception to avoid a chain of warning via sentry and other internal tools. I simply hoped in a return false but handler is not expected to return values.


回答1:


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;
    }


来源:https://stackoverflow.com/questions/57096343/laravel-can-i-fail-well-in-an-handle-of-a-job

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!