mirror of
https://github.com/DrizzleTime/Foxel.git
synced 2026-09-05 15:47:00 +08:00
feat: Add global exception handling
This commit is contained in:
@@ -2,12 +2,13 @@ from dotenv import load_dotenv
|
|||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from services.middleware.exception_handler import global_exception_handler
|
||||||
|
from services.middleware.logging_middleware import LoggingMiddleware
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
from api.routers import include_routers
|
from api.routers import include_routers
|
||||||
from db.session import close_db, init_db
|
from db.session import close_db, init_db
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from api.middleware import LoggingMiddleware
|
|
||||||
from services.adapters.registry import runtime_registry
|
from services.adapters.registry import runtime_registry
|
||||||
|
|
||||||
|
|
||||||
@@ -29,6 +30,7 @@ def create_app() -> FastAPI:
|
|||||||
)
|
)
|
||||||
include_routers(app)
|
include_routers(app)
|
||||||
app.add_middleware(LoggingMiddleware)
|
app.add_middleware(LoggingMiddleware)
|
||||||
|
app.add_exception_handler(Exception, global_exception_handler)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from fastapi import Request, status
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
from services.logging import LogService
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
async def global_exception_handler(request: Request, exc: Exception):
|
||||||
|
"""
|
||||||
|
全局异常处理
|
||||||
|
"""
|
||||||
|
error_details = {
|
||||||
|
"method": request.method,
|
||||||
|
"url": str(request.url),
|
||||||
|
"headers": dict(request.headers),
|
||||||
|
"exception": str(exc),
|
||||||
|
"traceback": traceback.format_exc(),
|
||||||
|
}
|
||||||
|
await LogService.error(
|
||||||
|
source="global_exception_handler",
|
||||||
|
message=f"Unhandled exception: {exc}",
|
||||||
|
details=error_details
|
||||||
|
)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
|
content={"error": "Internal Server Error", "detail": str(exc)},
|
||||||
|
)
|
||||||
@@ -43,4 +43,4 @@ class LoggingMiddleware(BaseHTTPMiddleware):
|
|||||||
|
|
||||||
await LogService.api(message, details, user_id)
|
await LogService.api(message, details, user_id)
|
||||||
|
|
||||||
return response
|
return response
|
||||||
Reference in New Issue
Block a user