"""Consistent API error shape ``{error:{code,message}}`` (SPEC ยง9.1).""" from __future__ import annotations from typing import NoReturn from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException def api_error(status_code: int, code: str, message: str) -> HTTPException: """Build an :class:`HTTPException` carrying the ``{code,message}`` detail.""" return HTTPException(status_code=status_code, detail={"code": code, "message": message}) def raise_api_error(status_code: int, code: str, message: str) -> NoReturn: """Raise :func:`api_error` (typed as ``NoReturn`` for control-flow clarity).""" raise api_error(status_code, code, message) async def _handler(request: Request, exc: StarletteHTTPException) -> JSONResponse: detail = exc.detail if isinstance(detail, dict) and "code" in detail: body = {"error": detail} else: body = {"error": {"code": "http_error", "message": str(detail)}} headers = getattr(exc, "headers", None) return JSONResponse(status_code=exc.status_code, content=body, headers=headers) def register_error_handlers(app: FastAPI) -> None: """Install the error-shape handler for all HTTP exceptions.""" app.add_exception_handler(StarletteHTTPException, _handler) # type: ignore[arg-type] app.add_exception_handler(HTTPException, _handler) # type: ignore[arg-type]