29 lines
953 B
Python
29 lines
953 B
Python
import http
|
|
from fastapi import FastAPI, HTTPException, Request
|
|
from pydantic import ValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from uvicorn.server import logger
|
|
|
|
exceptions = [Exception, HTTPException, ValidationError]
|
|
|
|
|
|
async def general_exception_handler(request: Request, e: Exception):
|
|
logger.error(f"[异常处理] 发生异常: {e}")
|
|
status_code = http.HTTPStatus.INTERNAL_SERVER_ERROR
|
|
detail = str(e)
|
|
message = "发生了一些错误"
|
|
if isinstance(e, HTTPException):
|
|
status_code = e.status_code
|
|
message = e.detail
|
|
return JSONResponse(
|
|
status_code=status_code,
|
|
content={"detail": detail, "message": message},
|
|
)
|
|
|
|
|
|
def install(app: FastAPI):
|
|
logger.info("[异常处理] 开始加载异常处理器")
|
|
for exception in exceptions:
|
|
app.add_exception_handler(exception, general_exception_handler)
|
|
logger.info("[异常处理] 异常处理器加载完成")
|