Skip to content

pixano_inference.api.v1.errors

Consistent error envelope and exception handlers for the API.

Every error response has the shape {"error": {"code", "message", "requestId"}}. Unhandled exceptions never leak their text to the client; the full traceback is logged server-side under the same request id.

register_exception_handlers(app)

Install the error-envelope exception handlers on app.

Source code in pixano_inference/api/v1/errors.py
def register_exception_handlers(app: FastAPI) -> None:
    """Install the error-envelope exception handlers on *app*."""

    @app.exception_handler(HTTPException)
    async def _http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
        code = _STATUS_CODES.get(exc.status_code, "error")
        return _envelope(exc.status_code, code, jsonable_encoder(exc.detail), _request_id(request))

    @app.exception_handler(RequestValidationError)
    async def _validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
        # jsonable_encoder makes validator error context (e.g. a raised ValueError) JSON-safe.
        return _envelope(422, "validation_error", jsonable_encoder(exc.errors()), _request_id(request))

    @app.exception_handler(Exception)
    async def _unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
        request_id = _request_id(request)
        logger.exception("Unhandled error [%s] on %s %s", request_id, request.method, request.url.path)
        return _envelope(500, "internal_error", "Internal server error.", request_id)