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


How to access exception thrown in failed Laravel queued Job

我正在使用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? ...
    }
}

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

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

应该可以了

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

我假设你做了failed方法?

您可以使用以下代码:

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

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

你可以尝试这样做

   /**
 * failed
 *
 * @param  mixed $throwable
 * @return void
 */
public function failed(Throwable $throwable){
    dd($throwable);
}