"""Map service exceptions onto HTTP responses for /api/v1.""" from __future__ import annotations import traceback from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from src.api.errors import HTTP_UNPROCESSABLE_ENTITY, ApiError HTTP_INTERNAL_ERROR = 500 def _body(code: str, message: str, detail=None) -> dict: return {"code": code, "message": message, "detail": detail} async def _api_error(_request: Request, exc: ApiError) -> JSONResponse: headers = {} # Give 429s a Retry-After so ordinary HTTP clients back off correctly. retry_after = exc.extra.get("retry_after_s") if retry_after is not None: headers["Retry-After"] = str(int(retry_after)) return JSONResponse(status_code=exc.status, content=exc.to_body(), headers=headers) def _describe(failure: dict) -> str: """Render one Pydantic failure as `field: message`.""" # loc is ("body", "field", ...) — drop the location kind, keep the path. path = ".".join(str(part) for part in failure.get("loc", ())[1:]) message = failure.get("msg", "invalid value") return f"{path}: {message}" if path else message async def _request_validation( _request: Request, exc: RequestValidationError, ) -> JSONResponse: """Give schema rejections the same body shape as every other error. FastAPI's default 422 body is a bare `detail` list, which would force callers to parse two different error formats. """ failures = exc.errors() summary = "; ".join(_describe(f) for f in failures) or "Invalid request" return JSONResponse( status_code=HTTP_UNPROCESSABLE_ENTITY, content=_body("invalid_request", summary, {"fields": failures}), ) async def _unhandled(_request: Request, exc: Exception) -> JSONResponse: """Last resort: log the traceback, return an opaque 500. Internal exception text can carry paths and model internals, so it is logged rather than returned. """ print(f"[API v1] Unhandled {type(exc).__name__}: {exc}") traceback.print_exc() return JSONResponse( status_code=HTTP_INTERNAL_ERROR, content=_body("internal_error", "The server failed to process this request."), ) def install(app: FastAPI) -> None: app.add_exception_handler(ApiError, _api_error) app.add_exception_handler(RequestValidationError, _request_validation) app.add_exception_handler(Exception, _unhandled)