You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中ThrottleRequestsException未返回JSON响应问题

问题分析与解决方案

你错误使用了reportable方法——这个方法的作用是报告异常(如记录日志),而非自定义异常的响应输出。要自定义限流异常的返回格式,需要使用renderable方法来拦截并处理异常响应。

修改后的异常处理器代码

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (ThrottleRequestsException $e, $request) {
            // 判断是否为API请求
            if ($request->is('api/*')) {
                return response()->json([
                    'message' => '请求过于频繁,请稍后再试。'
                ], 429);
            }
        });
    }
}

额外检查项

  • 确认你的optouts路由确实在api路由组下(即路由路径以api/开头)
  • 确保请求头中包含Accept: application/json,Laravel会根据这个头自动优先返回JSON响应(即使不自定义异常处理,也能触发默认的JSON错误响应)
  • 验证路由是否正确应用了throttle中间件

内容的提问来源于stack exchange,提问作者Ryan H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 08:21:34