Laravel8队列捕获异常任务没有释放回队列

本人laravel版本是8.X
看了文档队列《Laravel 8 中文文档》
里面的一句话:如果在处理任务时抛出异常,则任务将自动释放回队列,以便再次尝试。直到它被尝试的次数达到你的申请允许的最大次数,该任务才将继续被释放。

<?php

namespace App\Jobs;


use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;

/**
 * 出单任务
 *
 * Class PolicyOrder
 * @package App\Jobs
 */
class PolicyOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;

    /**
     * 任务尝试次数
     *
     * @var int
     */
    public $tries = 5;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {

                //发起出单请求
                $response = Http::asForm()->post(env("JSS_DOMAIN") . '/api/createpolicy/index', ['id'=>1]);
                $response = json_decode($response->body(), true);
                print_r($response);
                if ($response['status'] != 0) { //失败的情况
                    throw new \Exception($response['statusInfo']);
                } else { //成功
                    //更新订单号
                    UserTrip::where(['id' => $this->params['user_trip_id']])
                        ->update(['order_no' => $response['data']['orderno']]);
                }

        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
    }
}

我也加了try,catch,模拟运行,第一次失败,那捕获异常了,正常会再次执行,直到5次,可是并没有,只运行一次。我在catch里面加$this->release(5)就可以了。所以我不知道是文档写的不对还是我理解不对?大伙帮忙看看

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

文档上写的也是抛出异常时自动再次尝试,并不是捕获异常

你既然自己捕获了异常,当然得按你写的来

你捕获异常只记录了日志,所有没有重试

你可以在 catch 中重新抛出异常

} catch (\Exception $e) {
    Log::error($e->getMessage());

    throw $e; 
}

或按你写的重新放回队列

} catch (\Exception $e) {
    Log::error($e->getMessage());

    $this->release();
}
1年前 评论
bluememory (楼主) 1年前
讨论数量: 2

文档上写的也是抛出异常时自动再次尝试,并不是捕获异常

你既然自己捕获了异常,当然得按你写的来

你捕获异常只记录了日志,所有没有重试

你可以在 catch 中重新抛出异常

} catch (\Exception $e) {
    Log::error($e->getMessage());

    throw $e; 
}

或按你写的重新放回队列

} catch (\Exception $e) {
    Log::error($e->getMessage());

    $this->release();
}
1年前 评论
bluememory (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!