, \Psr\Log\LogLevel::*> */ protected $levels = [ // ]; /** * A list of the exception types that are not reported. * @var array> */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed to the session on validation exceptions. * @var array */ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. */ public function register(): void { $this->reportable(function (Throwable $e) { // }); } /** * Render an exception into an HTTP response. * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return \Symfony\Component\HttpFoundation\Response * @throws \Throwable */ public function render($request, Throwable $e) { // API 异常处理 if ($request->expectsJson() || $request->is('api/*')) { return $this->handleApiException($request, $e); } return parent::render($request, $e); } /** * 处理 API 异常 * @param \Illuminate\Http\Request $request * @param \Throwable $e * @return \Illuminate\Http\JsonResponse */ private function handleApiException( Request $request, Throwable $e ): JsonResponse { // 业务异常 if ($e instanceof CustomException) { return app(ApiResponseService::class)->businessError( $e->getMessage(), $e->getCode() ?: 400 ); } // 认证异常 if ($e instanceof AuthenticationException) { return app(ApiResponseService::class)->unauthorized( $e->getMessage() ?: __('exception.exception_handler.login') ); } // 验证异常 if ($e instanceof ValidationException) { return app(ApiResponseService::class)->businessError( $e->getMessage(), 422, 422 ); } // 模型未找到异常 if ($e instanceof ModelNotFoundException) { return app(ApiResponseService::class)->businessError( __('exception.exception_handler.resource'), 404 ); } // 路由未找到异常 if ($e instanceof NotFoundHttpException) { return app(ApiResponseService::class)->businessError( __('exception.exception_handler.api'), 404 ); } // HTTP 异常 if ($e instanceof HttpException) { $statusCode = $e->getStatusCode(); if ($statusCode === 403) { return app(ApiResponseService::class)->businessError( __('exception.exception_handler.role'), 403 ); } if ($statusCode === 429) { return app(ApiResponseService::class)->businessError( __('exception.exception_handler.frequent'), 429 ); } return app(ApiResponseService::class)->systemError( $e->getMessage() ?: __('exception.exception_handler.system') ); } // 其他异常 return app(ApiResponseService::class)->systemError( __('exception.exception_handler.system') . ':' . $e->getMessage() ); } }