Skip to content

Exceptions

APIException

Raising exception with useful error message is a good practice and there's RFC 9457 that suggests how to do it. FastAPI has this on its roadmap however it's not implemented yet.

FastAPI batteries custom exception class APIException that can be used to raise exceptions following RFC 9457.

from fastapi import FastAPI, status

from fastapi_batteries.fastapi.exceptions import APIException, get_api_exception_handler

app = FastAPI()

app.add_exception_handler(APIException, get_api_exception_handler())


@app.get("/raises-exception/")
async def get_index():
    raise APIException(
        status=status.HTTP_400_BAD_REQUEST,
        title="This is a test exception.",
    )

fastapi_batteries__api_exception

Right now, It only handles APIException and convert to RFC 9457 compliant response. I'm planning to also handle Pydantic's validation error and convert to RFC 9457 compliant response. If you have any other suggestions, please let me know.