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.
This commit is contained in:
+15
-2
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user