Created
June 7, 2024 05:31
-
-
Save dcki/186dd537e61653be1d827a116bc40d21 to your computer and use it in GitHub Desktop.
Customize SanicException response body
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from sanic import response, Sanic | |
| from sanic.exceptions import SanicException | |
| from sanic.request import Request | |
| from sanic.response import HTTPResponse | |
| # NOTE: This error should only be raised after add_custom_error_handler() | |
| # has been called to register a custom error handler on the | |
| # currently-running app. | |
| class CustomSanicException(SanicException): | |
| def __init__(self, *args, body: object, **kwargs) -> None: | |
| super().__init__(*args, **kwargs) | |
| # (At first glance it seems like `self.message` could be used as the | |
| # `body` argument to `response.json()`, but it seems that | |
| # `Exception.__init__()` converts `message` to a string before assigning | |
| # it to `self.message`.) | |
| # | |
| # (It also seems like the `message` argument to `__init__()` could be | |
| # assigned to `self.body`, but SanicException (and maybe also Exception) | |
| # have that argument type-annotated with an incompatible type that | |
| # doesn't allow `message` to be a dict, which is commonly what we want | |
| # the body to be.) | |
| self.body = body | |
| # Adds an error handler that catches CustomSanicException errors and responds | |
| # with a JSON body containing the value of `exception.body`. | |
| def add_custom_error_handler(app: Sanic) -> None: | |
| @app.exception(CustomSanicException) | |
| async def handle_custom_sanic_exception( | |
| request: Request, exception: CustomSanicException) -> HTTPResponse: | |
| return response.json( | |
| status=exception.status_code, body=exception.body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment