2026-07-17 23:20:34 +02:00
|
|
|
"""Consistent API error shape ``{error:{code,message}}`` (SPEC §9.1)."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from typing import NoReturn
|
|
|
|
|
|
|
|
|
|
from fastapi import FastAPI, HTTPException, Request
|
2026-10-14 22:08:06 +02:00
|
|
|
from fastapi.exceptions import RequestValidationError
|
2026-07-17 23:20:34 +02:00
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
2026-10-14 22:08:06 +02:00
|
|
|
async def _validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
|
|
|
|
"""A malformed request, in the usual error shape. Names the first field at
|
|
|
|
|
fault and what is wrong with it — enough to show the user — but not the
|
|
|
|
|
whole request model the framework's own answer would spell out."""
|
|
|
|
|
errors = exc.errors()
|
|
|
|
|
first = errors[0] if errors else {}
|
|
|
|
|
loc = [str(p) for p in first.get("loc", ()) if p not in ("body", "query", "path")]
|
|
|
|
|
field = loc[-1] if loc else ""
|
|
|
|
|
reason = str(first.get("msg", "invalid value"))
|
|
|
|
|
message = f"{field}: {reason}" if field else reason
|
|
|
|
|
return JSONResponse(
|
|
|
|
|
status_code=422, content={"error": {"code": "validation_error", "message": message}}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2026-07-17 23:20:34 +02:00
|
|
|
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]
|
2026-10-14 22:08:06 +02:00
|
|
|
app.add_exception_handler(RequestValidationError, _validation_handler) # type: ignore[arg-type]
|