1

I know that, if a job throw an Exception, the job fails, and will be retried automatically from queue worker in a few seconds.

My question is: can i fail in a controlled way?

I'd like to catch exceptions, create a more smal log, and, for example, return false to mark job as failed.

Is there a way?

Precisation: I DO NOT want to HANDLE failure. I want to provocate a failure without throwing exceptions. I some edge cases I need that jobs fails. But I also need to avoid to throw Exception to avoid a chain of warning via sentry and other internal tools. I simply hoped in a return false but handler is not expected to return values.

realtebo
  • 23,922
  • 37
  • 112
  • 189
  • https://laravel.com/docs/5.7/queues#failed-job-events You can do what ever you like when the failed job triggers the Queue::failing(function (JobFailed $event) {}): call. – Petay87 Jul 18 '19 at 14:18

1 Answers1

4

If you want to handle all failing commands, then go for Failed job events like Petay suggested. If you want to handle failure for a single job, you can implement the failed method, just like you implemented the handle method.

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:

class ProcessPodcast implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        // Handle job and throw exception
    }

    public function failed(Exception $exception)
    {
        // Create log file
    }
}

Marking a job as failed can be done using the --tries option when calling the worker.

Then, when running your queue worker, you should specify the maximum number of times a job should be attempted using the --tries switch on the queue:work command. If you do not specify a value for the --tries option, jobs will be attempted indefinitely:

php artisan queue:work redis --tries=3

In case you want to trigger a failure manually you can either throw an exception or return the statuscode like so:

    public function handle(): int
    {
        if($somethingWentWrong) {
            return -2;
        }

        return 0;
    }
PtrTon
  • 3,705
  • 2
  • 14
  • 24
  • Sorry, probably my question was bad-written. I do now want to handle failures. I want to provocate a failure without throwing an exception. I add this note in the OP – realtebo Jul 22 '19 at 08:00
  • Oh, I didn't know handle could return a value !! Yes, it resolves – realtebo Jul 23 '19 at 10:22