Laravel:我能否在Job的handle()中失败? [英] Laravel: Can I fail 'well' in an handle() of a Job?

查看:382
本文介绍了Laravel:我能否在Job的handle()中失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果作业抛出异常,则该作业将失败,并且将在几秒钟内从队列工作器中自动重试.

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?

我想捕获异常,创建更小的日志,例如,返回false以将作业标记为失败.

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

有办法吗?

精确化:我不想处理失败.我想提倡一个失败而不抛出异常.我在某些情况下需要工作失败.但是我还需要避免引发Exception,以避免通过哨兵和其他内部工具发出警告链.我只是希望在return false中,但是处理程序不应返回值.

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.

推荐答案

如果要处理所有失败的命令,请尝试建议使用Petay . 如果要处理单个作业的失败,则可以实现failed方法,就像实现handle方法一样.

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

在致电工作人员时,可以使用--tries选项将作业标记为失败.

Marking a job as failed can be done using the --tries option when calling the worker.

然后,在运行队列工作器时,应使用queue:work命令上的--tries开关指定尝试作业的最大次数.如果未为--tries选项指定值,则将无限期尝试作业:

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

这篇关于Laravel:我能否在Job的handle()中失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆