如何让Laravel应用以JSON格式返回所有异常(含HTTP状态码)
Laravel统一异常返回JSON格式配置方案
你之前的代码误用了reportable方法——这个方法负责异常上报(比如日志记录),不会影响前端收到的响应内容。要实现任意异常都返回指定格式的JSON响应,需要通过重写render方法或者注册renderable回调来处理。
方法一:重写render方法(推荐)
直接修改App/Exceptions/Handler.php中的render方法,统一构造JSON响应:
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Validation\ValidationException; use Symfony\Component\HttpKernel\Exception\HttpException; use Throwable; class Handler extends ExceptionHandler { protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; public function register(): void { // 保留异常上报逻辑(比如默认日志记录) $this->reportable(function (Throwable $e) { // 可自定义日志上报逻辑,比如发送到监控平台 }); } /** * 重写异常渲染逻辑,返回统一JSON格式 */ public function render($request, Throwable $e) { // 初始化响应数据结构 $response = [ 'errors' => [], 'exception' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'statusCode' => 500, // 默认500服务器错误 ]; // 处理HTTP类异常(如404、403、401等) if ($e instanceof HttpException) { $response['statusCode'] = $e->getStatusCode(); } // 处理验证异常,填充错误字段 if ($e instanceof ValidationException) { $response['errors'] = $e->errors(); $response['statusCode'] = $e->status; } // 返回JSON响应 return response()->json($response, $response['statusCode']); } }
方法二:使用renderable回调
如果不想完全重写render方法,也可以在register方法中注册renderable回调:
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Validation\ValidationException; use Throwable; class Handler extends ExceptionHandler { protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; public function register(): void { $this->reportable(function (Throwable $e) { // 异常上报逻辑 }); // 注册异常渲染回调 $this->renderable(function (Throwable $e, $request) { $statusCode = method_exists($e, 'getStatusCode') ? $e->getStatusCode() : 500; $errors = []; // 处理验证错误 if ($e instanceof ValidationException) { $errors = $e->errors(); $statusCode = $e->status; } return response()->json([ 'errors' => $errors, 'exception' => get_class($e), 'file' => $e->getFile(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'statusCode' => $statusCode, ], $statusCode); }); } }
关键说明
get_class($e)用于获取异常的完整类名,对应示例中的exception字段$e->getFile()和$e->getLine()分别返回异常发生的文件和行号- 针对验证异常单独处理
errors字段,确保验证失败时返回具体的错误信息 - 自动识别HTTP异常的状态码(如404、403),非HTTP异常默认返回500状态码
内容的提问来源于stack exchange,提问作者xJosAntonio A
相关产品推荐
相关产品推荐

