如何访问失败的Laravel排队作业中引发的异常

Was*_*sim 2 php laravel

我正在使用Laravel 5.2 Job并对其进行排队。当失败时,将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? ...
    }
}
Run Code Online (Sandbox Code Playgroud)

在该failed()方法中,如何访问Job失败时引发的异常?

我知道我可以捕获Exception,handle()但是我想知道它是否可以在其中访问failed()

Cap*_*ext 7

这应该工作

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...
}
Run Code Online (Sandbox Code Playgroud)

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


fic*_*489 5

您可以使用以下代码:

public function failed(Exception $exception)
{
    // Send user notification of failure, etc...
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我相信你可以使用 `Throwable` 代替 `Exception`,这也将捕获自定义异常 (2认同)