> */ 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->reportable(function (Throwable $e) { // }); } // 异常处理 public function report(Throwable $exception) { parent::report($exception); // 调用父类的 report 方法,记录日志 } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Throwable $exception * @return \Symfony\Component\HttpFoundation\Response */ public function render($request, Throwable $exception) { // sanctum 异常处理 if ($exception instanceof RouteNotFoundException || $exception instanceof AuthenticationException) { return response()->json([ 'code' => 401, 'msg' => "登录已过期", ], 401); } // 捕获 NotFoundHttpException 异常并自定义处理 if ($exception instanceof NotFoundHttpException) { return response()->view('errors.404', [], 404); // 返回自定义的 404 错误页面 } // 捕获 ValidationException 并返回统一的 JSON 错误响应 if ($exception instanceof ValidationException) { $errors = $exception->errors(); return response()->json([ 'code' => 0, // 'msg' => '参数校验失败', 'msg' => '参数校验失败 ' . array_keys($errors)[0] . ' - ' . reset($errors)[0], ], 422); } // 你可以在这里捕获所有的异常,进行日志记录 if ($exception instanceof \Throwable) { // 记录日志 Log::error($exception); // 返回统一的错误响应 return response()->json(['code' => 0, 'msg' => '请求异常'], 400); } // 如果是其他类型的异常,交给父类处理 return parent::render($request, $exception); } }