Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

queue - Laravel: Can I fail 'well' in an handle() of a Job?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...