From 292b18760cee7bb0898626a90305b9099358bc45 Mon Sep 17 00:00:00 2001 From: wren <“porlong@qq.com”> Date: Thu, 30 Apr 2026 11:13:07 +0800 Subject: [PATCH] fix: add global exception handler for BusinessException BusinessException (and its subclass LeauditException) had no FastAPI exception handler, so they escaped as unhandled 500s even when carrying the correct status code (e.g. 403). Add a handler that renders the status code and message as a proper JSON response. --- fastapi_admin/app.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/fastapi_admin/app.py b/fastapi_admin/app.py index 8f5397d..473a655 100644 --- a/fastapi_admin/app.py +++ b/fastapi_admin/app.py @@ -7,13 +7,14 @@ import sys from contextlib import asynccontextmanager from pathlib import Path -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import Response +from fastapi.responses import JSONResponse, Response from fastapi_admin.config import APP_NAME, APP_CORS_ORIGINS from fastapi_admin.config._loader import _find_project_root from fastapi_common.fastapi_common_storage.oss_client import OssClient +from fastapi_common.fastapi_common_web.exception.Base.BusinessException import BusinessException # 确保项目根在 sys.path _PROJECT_ROOT = _find_project_root() @@ -61,6 +62,18 @@ def create_app() -> FastAPI: allow_headers=["*"], ) + # 统一业务异常处理 + @app.exception_handler(BusinessException) + async def handle_business_exception(request: Request, exc: BusinessException): + return JSONResponse( + status_code=exc.status.value, + content={ + "code": exc.status.value, + "message": exc.message, + "data": None, + }, + ) + # 注册控制器 from fastapi_admin.bootstrap_parts.controllers import register_controllers register_controllers(app)