Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
nguyen1tech opened this issue Apr 7, 2024 · 1 comment

Comments

@nguyen1tech
Copy link

nguyen1tech commented Apr 7, 2024

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
Copy link
Owner

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants