In Laravel while running Redis queues, I'm unable to get the failed method called in my Job class. I want to make sure I can properly log them and that they are written to the failed_jobs table.
Laravel documentation about queues states
You may define a failed method directly on your job class, allowing you to perform job specific clean-up when a failure occurs. This is the perfect location to send an alert to your users or revert any actions performed by the job. The Exception that caused the job to fail will be passed to the failed method:
I'm not 100% sure what Laravel consider to be "the exception that caused the job to fail". Below is a very simple job class. All that's appearing in my logs is It did not work and exception caught.
I'm launching this queue with the following command, specifically setting tries to 1 so it doesn't attempt to re-run the job.
php artisan queue:work redis --queue=widgets --tries=1
How can I get the failed method to be called and the job to appear in the failed_jobs table?
<?php
namespace App\Jobs;
use Exception;
use App\Processors\WidgetProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class WidgetJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct($widget)
{
$this->widget = $widget;
}
public function handle(WidgetProcessor $processor)
{
Redis::throttle('WidgetJob')->allow(5)->every(60)->then(function () use ($processor) {
try {
$var = false;
if($var == false) {
Log::notice('It did not work');
throw new Exception;
} else {
Log::notice('It worked');
}
} catch(Exception $e) {
Log::notice('Exception caught');
}
}, function () {
return $this->release(5);
});
}
public function failed(Exception $exception)
{
Log::notice('failed was called');
}
}
handlefunction return isvoid. Without an exception, the job was successfully executed. Let the exception bubble up so Laravel will tag it as failed. - Marco Aurélio Deleu