import logging from uuid import uuid4 from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from app.core.exceptions import AppError logger = logging.getLogger(__name__) def register_exception_handlers(app: FastAPI) -> None: @app.exception_handler(AppError) async def handle_app_error(request: Request, exc: AppError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={ "error": { "code": exc.code, "message": exc.message, "details": exc.details, "request_id": getattr(request.state, "request_id", None), } }, ) @app.exception_handler(Exception) async def handle_unexpected_error(request: Request, exc: Exception) -> JSONResponse: error_id = str(uuid4()) logger.exception("Unhandled exception error_id=%s", error_id) return JSONResponse( status_code=500, content={ "error": { "code": "INTERNAL_SERVER_ERROR", "message": "服务器内部错误", "error_id": error_id, "request_id": getattr(request.state, "request_id", None), } }, )