如何访问失败的 Laravel 排队作业中抛出的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40084712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:37:33  来源:igfitidea点击:

How to access exception thrown in failed Laravel queued Job

phplaravel

提问by Wasim

I'm using a Laravel 5.2 Joband queuing it. When it fails it fires the failed()method on the job:

我正在使用 Laravel 5.2Job并将其排队。当它失败时,它会触发工作中的failed()方法:

class ConvertJob extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, DispatchesJobs;


    public function __construct()
    {

    }

    public function handle()
    {
        // ... do stuff and fail ...
    }

    public function failed()
    {
        // ... what exception was thrown? ...
    }
}

In the failed()method, how do I access the exception that was thrown when the Jobfailed?

failed()方法中,如何访问Job失败时抛出的异常?

I understand I can catch the Exception in handle()but I wanted to know if it's accessable in failed()

我知道我可以捕获异常,handle()但我想知道它是否可以在failed()

采纳答案by Captain Hypertext

This should work

这应该工作

public function handle()
{
    // ... do stuff
    $bird = new Bird();

    try {
        $bird->is('the word');
    }
    catch(Exception $e) {
        // bird is clearly not the word
        $this->failed($e);
    }
}

public function failed($exception)
{
    $exception->getMessage();
    // etc...
}

I'm assuming you made the failedmethod? If that's a thing in Laravel, this is the first I've seen of it.

我假设你做了这个failed方法?如果这是 Laravel 中的东西,这是我第一次看到它。

回答by fico7489

you can use this code :

您可以使用此代码:

public function failed(Exception $exception)
{
    // Send user notification of failure, etc...
}

but it is available from laravel 5.3. version. For older laravel versions you can use some not elegant solutions like @Capitan Hypertext suggested.

但它可以从 laravel 5.3 获得。版本。对于较旧的 Laravel 版本,您可以使用一些不太优雅的解决方案,例如建议的 @Capitan Hypertext。