import logging from fastapi import FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse log = logging.getLogger("fraud.errors") def install_exception_handlers(app: FastAPI) -> None: @app.exception_handler(RequestValidationError) async def _validation(_: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={ "error": "VALIDATION_ERROR", "message": "Request validation failed", "details": {"errors": exc.errors()}, }, ) @app.exception_handler(HTTPException) async def _http(_: Request, exc: HTTPException): detail = exc.detail if isinstance(detail, dict) and "error" in detail: payload = { "error": detail.get("error", "ERROR"), "message": detail.get("message", ""), "details": detail.get("details"), } else: payload = {"error": "ERROR", "message": str(detail), "details": None} return JSONResponse(status_code=exc.status_code, content=payload) @app.exception_handler(Exception) async def _unhandled(_: Request, exc: Exception): log.exception("Unhandled exception: %s", exc) return JSONResponse( status_code=500, content={"error": "INTERNAL_ERROR", "message": "Internal server error", "details": None}, )