Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access exception thrown in failed Laravel queued Job

Tags:

php

laravel

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

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 Job failed?

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

like image 355
Wasim Avatar asked Oct 17 '16 11:10

Wasim


2 Answers

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 failed method? If that's a thing in Laravel, this is the first I've seen of it.

like image 128
Captain Hypertext Avatar answered Oct 17 '22 03:10

Captain Hypertext


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.

like image 31
fico7489 Avatar answered Oct 17 '22 04:10

fico7489