from fastapi import FastAPI, Request from fastapi.responses import JSONResponse class ApiError(Exception): """API error rendered as the protocol's {detail, code} problem shape.""" def __init__(self, status_code: int, detail: str, code: str) -> None: self.status_code = status_code self.detail = detail self.code = code def register_exception_handlers(app: FastAPI) -> None: @app.exception_handler(ApiError) async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={"detail": exc.detail, "code": exc.code}, )