"""Consistent error model: every error response is {"detail": str, "code": str, "request_id": str}.""" from __future__ import annotations from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException class ApiError(Exception): def __init__(self, status: int, code: str, detail: str, extra: dict | None = None, headers: dict | None = None): super().__init__(detail) self.status, self.code, self.detail, self.extra, self.headers = status, code, detail, extra or {}, headers def _body(request: Request, code: str, detail: str, extra: dict | None = None) -> dict: return {"detail": detail, "code": code, "request_id": getattr(request.state, "request_id", None), **(extra or {})} def install(app: FastAPI) -> None: @app.exception_handler(ApiError) async def _api(request: Request, exc: ApiError): return JSONResponse(_body(request, exc.code, exc.detail, exc.extra), status_code=exc.status, headers=exc.headers) @app.exception_handler(StarletteHTTPException) async def _http(request: Request, exc: StarletteHTTPException): code = {401: "UNAUTHENTICATED", 403: "FORBIDDEN", 404: "NOT_FOUND", 405: "METHOD_NOT_ALLOWED"}.get(exc.status_code, "HTTP_ERROR") return JSONResponse(_body(request, code, str(exc.detail)), status_code=exc.status_code) @app.exception_handler(RequestValidationError) async def _val(request: Request, exc: RequestValidationError): errs = [{"loc": list(e.get("loc", [])), "msg": e.get("msg")} for e in exc.errors()] return JSONResponse(_body(request, "VALIDATION", "request validation failed", {"errors": errs}), status_code=422) @app.exception_handler(Exception) async def _any(request: Request, exc: Exception): import logging logging.getLogger("fpt.api").exception("unhandled error") return JSONResponse(_body(request, "INTERNAL", f"{type(exc).__name__}"), status_code=500)