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
相关产品推荐
相关产品推荐

