Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a failed job laravel

Tags:

laravel

I am doing multiple calls to different api's on my cron job, like:

foreach ($transactions as $transaction) {
    $job = (new SendApplicationToBank($transaction));
    $this->dispatch($job);
}

One transaction has many banks so I am sending a transaction to all banks related:

Job:

public function handle(){
    try {
        $result = app($bankClass)::sendLoanApplication($this->transaction);
    } catch (Exception $e) {
        //Silent fail
    }
}

The problem is that its failing on the first bank and just keeps retrying.

How should go and cofigure so If a job fails just release back to queue and continue the next one ?

Results:

php artisan queue:listen

like image 546
Dell Christopher Avatar asked Mar 08 '18 13:03

Dell Christopher


People also ask

How do I rerun failed jobs in Laravel?

You can retry all failed Jobs by running: php artisan queue:retry all . The question is for Laravel 4, but yes. From Laravel 5 and forward this is the correct answer.


2 Answers

You should not catch the Exception to let the job fail properly. Now you are catching it and doing nothing (//Silent fail)

You should make a table in your database to catch the failed jobs automatically with:

php artisan queue:failed-table

In the script running your queue you should add the number of tries before failing:

php artisan queue:listen --tries=3

It's also smart to add some kind of timeout:

php artisan queue:listen --tries=3 --timeout=60

And you can also call a webhook on fail by adding a failed method to you job:

public function failed()
{
    // Called when the job is failing...
}
like image 93
Björn Avatar answered Oct 10 '22 22:10

Björn


Running a command with limited tries you can run the following command

php artisan queue:work --retry=3

it will try to run your job only three-time

and programmatically you can use

    public $tries = 3;

in your job class

Hope this helps

like image 45
Romantic Dev Avatar answered Oct 10 '22 20:10

Romantic Dev