Spaces:
Running on Zero
Running on Zero
File size: 2,485 Bytes
35d8fb6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | """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)
|