85 lines
2.6 KiB
Python
85 lines
2.6 KiB
Python
"""
|
|
全局异常处理器模块
|
|
|
|
注册 FastAPI 全局异常处理器,统一处理应用异常。
|
|
"""
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
|
|
from core.exceptions import AppException
|
|
from logger.logging import get_logger
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
def register_exception_handlers(app: FastAPI) -> None:
|
|
"""
|
|
注册全局异常处理器
|
|
|
|
Args:
|
|
app: FastAPI 应用实例
|
|
"""
|
|
|
|
@app.exception_handler(AppException)
|
|
async def app_exception_handler(request: Request, exc: AppException):
|
|
"""处理应用自定义异常"""
|
|
logger.warning(f"AppException: {exc.message} (code={exc.code})")
|
|
return JSONResponse(
|
|
status_code=exc.code,
|
|
content={
|
|
"code": exc.code,
|
|
"msg": exc.message,
|
|
"data": exc.data
|
|
}
|
|
)
|
|
|
|
@app.exception_handler(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
"""处理 HTTP 异常"""
|
|
logger.warning(f"HTTPException: {exc.detail} (status={exc.status_code})")
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={
|
|
"code": exc.status_code,
|
|
"msg": str(exc.detail),
|
|
"data": None
|
|
}
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
"""处理请求验证错误"""
|
|
errors = exc.errors()
|
|
error_messages = []
|
|
for error in errors:
|
|
field = ".".join(str(loc) for loc in error["loc"])
|
|
msg = error["msg"]
|
|
error_messages.append(f"{field}: {msg}")
|
|
|
|
message = "; ".join(error_messages)
|
|
logger.warning(f"ValidationError: {message}")
|
|
|
|
return JSONResponse(
|
|
status_code=422,
|
|
content={
|
|
"code": 422,
|
|
"msg": f"参数验证失败: {message}",
|
|
"data": errors
|
|
}
|
|
)
|
|
|
|
@app.exception_handler(Exception)
|
|
async def general_exception_handler(request: Request, exc: Exception):
|
|
"""处理未捕获的异常"""
|
|
logger.exception(f"Unhandled exception: {exc}")
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={
|
|
"code": 500,
|
|
"msg": "服务器内部错误",
|
|
"data": None
|
|
}
|
|
)
|