diff --git a/sanic/exceptions.py b/sanic/exceptions.py index 16cd684d5b..ad2205ddfa 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -4,16 +4,20 @@ class SanicException(Exception): + message: str = "" + def __init__( self, message: Optional[Union[str, bytes]] = None, status_code: Optional[int] = None, quiet: Optional[bool] = None, ) -> None: - - if message is None and status_code is not None: - msg: bytes = STATUS_CODES.get(status_code, b"") - message = msg.decode("utf8") + if message is None: + if self.message: + message = self.message + elif status_code is not None: + msg: bytes = STATUS_CODES.get(status_code, b"") + message = msg.decode("utf8") super().__init__(message) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index a52d6567a9..1ccd55474c 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -235,6 +235,22 @@ def test_sanic_exception(exception_app): assert len(w) == 1 and "deprecated" in w[0].message.args[0] +def test_custom_exception_default_message(exception_app): + class TeaError(SanicException): + message = "Tempest in a teapot" + status_code = 418 + + exception_app.router.reset() + + @exception_app.get("/tempest") + def tempest(_): + raise TeaError + + _, response = exception_app.test_client.get("/tempest", debug=True) + assert response.status == 418 + assert b"Tempest in a teapot" in response.body + + def test_exception_in_ws_logged(caplog): app = Sanic(__file__)