*/ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. */ public function register(): void { // 处理可报告的异常 $this->reportable(function (Throwable $e) { // 可以在这里记录异常或执行其他操作 }); // 处理可渲染的异常 $this->renderable(function (\Exception $exception, Request $request) { // 检查请求是否为 API 请求 if ($request->is('api*')) { // 处理 JWT 相关的异常 if ($exception instanceof JWTException) { // 映射 JWT 异常到用户友好的消息 $mapExceptions = [ TokenInvalidException::class => '无效的token', TokenBlacklistedException::class => 'token 已被加入黑名单,请重新登录' ]; // 获取对应的错误消息 $msg = $mapExceptions[get_class($exception)] ?? $exception->getMessage(); return responseJsonAsUnAuthorized($msg); // 返回未授权的 JSON 响应 } // 拦截表单验证错误抛出的异常 elseif ($exception instanceof ValidationException) { return responseJsonAsBadRequest($exception->validator->errors()->first()); // 返回验证错误的 JSON 响应 } // 处理其他服务器错误 return responseJsonAsServerError($exception->getMessage()); } // 对于非 API 请求,返回服务器错误信息 return responseJsonAsServerError($exception->getMessage(), null); }); } }