"""Exception handlers + request-id middleware that emit the canonical error envelope on every non-2xx response.""" from __future__ import annotations import logging import uuid from typing import Any from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from app.schemas.error import ( ApiErrorEnvelope, ErrorCode, ErrorPayload, InternalErrorEnvelope, NotFoundEnvelope, ServiceUnavailableEnvelope, UnauthorizedEnvelope, ValidationErrorEnvelope, ) log = logging.getLogger(__name__) class ApiException(Exception): """Raise this from route handlers to emit a typed error envelope. Prefer this over ``HTTPException`` so the envelope carries an explicit ``ErrorCode`` and structured ``details``.""" def __init__(self, status_code: int, code: ErrorCode, message: str, details: dict[str, str] | None = None): super().__init__(message) self.status_code = status_code self.code = code self.message = message self.details = details or {} _STATUS_TO_CODE: dict[int, ErrorCode] = { 400: ErrorCode.bad_request, 401: ErrorCode.unauthorized, 404: ErrorCode.not_found, 422: ErrorCode.validation_error, 503: ErrorCode.service_unavailable, } # Maps status code → response model exposed in the OpenAPI spec. COMMON_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { 400: {"model": ValidationErrorEnvelope, "description": "Request payload failed validation."}, 404: {"model": NotFoundEnvelope, "description": "Resource does not exist."}, 503: {"model": ServiceUnavailableEnvelope, "description": "Pipeline not ready or upstream unavailable."}, 500: {"model": InternalErrorEnvelope, "description": "Unexpected server error."}, } def _request_id(request: Request) -> str: return getattr(request.state, "request_id", None) or str(uuid.uuid4()) def _envelope_json(code: ErrorCode, message: str, details: dict[str, str], request_id: str) -> dict: return ApiErrorEnvelope( error=ErrorPayload( code=code, message=message, details=details, request_id=request_id, ) ).model_dump(mode="json") def _json_response(status_code: int, envelope: dict, request_id: str) -> JSONResponse: return JSONResponse( status_code=status_code, content=envelope, headers={"X-Request-ID": request_id}, ) def install(app: FastAPI) -> None: """Wire middleware + handlers into the app.""" @app.middleware("http") async def request_id_middleware(request: Request, call_next): rid = request.headers.get("x-request-id") or str(uuid.uuid4()) request.state.request_id = rid try: response = await call_next(request) except Exception: # Fall through to the generic handler; ensure header is set # on whatever response that handler builds. raise response.headers["X-Request-ID"] = rid return response @app.exception_handler(ApiException) async def _api_exception_handler(request: Request, exc: ApiException): rid = _request_id(request) return _json_response( exc.status_code, _envelope_json(exc.code, exc.message, exc.details, rid), rid, ) @app.exception_handler(StarletteHTTPException) async def _http_exception_handler(request: Request, exc: StarletteHTTPException): rid = _request_id(request) code = _STATUS_TO_CODE.get(exc.status_code, ErrorCode.internal_server_error) detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail) return _json_response( exc.status_code, _envelope_json(code, detail, {}, rid), rid, ) @app.exception_handler(RequestValidationError) async def _validation_handler(request: Request, exc: RequestValidationError): rid = _request_id(request) details: dict[str, str] = {} for err in exc.errors(): loc = ".".join(str(p) for p in err.get("loc", [])[1:]) or "_" details[loc] = err.get("msg", "invalid") return _json_response( 422, _envelope_json( ErrorCode.validation_error, "request validation failed", details, rid, ), rid, ) @app.exception_handler(Exception) async def _unhandled_handler(request: Request, exc: Exception): rid = _request_id(request) log.exception("unhandled exception (request_id=%s): %s", rid, exc) return _json_response( 500, _envelope_json( ErrorCode.internal_server_error, "internal server error", {}, rid, ), rid, ) # Mark these as used so type checkers don't complain about the # closures being unused locals. _ = ( request_id_middleware, _api_exception_handler, _http_exception_handler, _validation_handler, _unhandled_handler, )