Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel exception handler for queue worker

I am having a weird issue while throwing the exception inside my beanstalkd job class. When I throw a simple exception (throw new \Exception();) outside the job class, it calls the report() method in App\Exceptions\Handler and I can do my tweaks there. But when I throw the exception inside the job class, it does not call the report() method. All the queue implementation is based on laravel documentation(https://laravel.com/docs/5.1/queues) and works great. What can be the reason for this? Any help would be highly appreciated.

like image 743
Tibin Paul Avatar asked Jun 07 '16 18:06

Tibin Paul


People also ask

What is exception handling in Laravel?

Reporting ExceptionsAll exceptions are handled by the App\Exceptions\Handler class. This class contains a register method where you may register custom exception reporting and rendering callbacks.

How does Laravel handle exception in API?

To do that, you can specify Route::fallback() method at the end of routes/api. php, handling all the routes that weren't matched. Route::fallback(function(){ return response()->json([ 'message' => 'Page Not Found. If error persists, contact [email protected]'], 404); });


1 Answers

Well, it had to be different for queues. If a job fails (throws an exception), you don't want to give the control to the Exception handler – you want to catch the error and mark the job as failed.

Look inside Worker.php (line 294+):

protected function raiseExceptionOccurredJobEvent($connection, Job $job, $exception)
{
    if ($this->events) {
        $data = json_decode($job->getRawBody(), true);

        $this->events->fire(new Events\JobExceptionOccurred($connection, $job, $data, $exception));
    }
}

See process() on lines 201-223 as well.

Laravel will catch the exception but will fire an Event to let you know there has been a problem. If you need to hook into it – just listen for this event.

like image 104
Denis Mysenko Avatar answered Sep 28 '22 07:09

Denis Mysenko