zhanymkanov / fastapi-best-practices

FastAPI Best Practices and Conventions we used at our startup
8.94k stars 675 forks source link

Adding `exception_handlers` for mapping from exceptions to the error responses #41

Open nguyen1tech opened 6 months ago

nguyen1tech commented 6 months ago

Thank you for sharing these best practices!

In our projects, we usually define a set of custom exceptions. These are mostly translated into unified error responses. Eg:

# exceptions.py
class InvalidInputError(Exception):
    error_code = ErrorCode.INVALID_INPUT
    error_message = "Invalid input error"

# Response
400 BadRequest
{
     "error": {
            "error_code": "INVALID_INPUT",
            "error_message": "Missing required field 'abc' ..."
      }
}

I think it would be great if we could have an exception_handlers.py file to handle the mappings from the exceptions to the corresponding error responses. Eg:

# exceptions.py
class InvalidInputError(Exception):
    error_code = ErrorCode.INVALID_INPUT
    error_message = "Invalid input error"

# exception_handlers.py
def invalid_input_exception_handler(_: Request, exc: InvalidInputError):
    error = ErrorItem(
        error_code=exc.error_code, error_message=exc.error_message
    )
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=jsonable_encoder(ErrorResponse(error=error)),
    )

def register_error_handlers(app: FastAPI) -> None:
    app.add_exception_handler(InvalidInputError, invalid_input_exception_handler)

# main.py
from exception_handlers import register_error_handlers

...
register_error_handlers(app=app)
...
zhanymkanov commented 5 months ago

Yeah, I was thinking of extending the practices with better exception handling in the next version. I wasn't doing it two years ago (only custom exceptions), but today most of my new projects include these handlers.

Thank you for sharing!