diff --git a/sanic/exceptions.py b/sanic/exceptions.py index 52e210580e..ce7c91db58 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -75,8 +75,9 @@ def __init__( quiet = quiet or getattr(self.__class__, "quiet", None) headers = headers or getattr(self.__class__, "headers", {}) if message is None: - if self.message: - message = self.message + cls_message = getattr(self.__class__, "message", None) + if cls_message: + message = cls_message elif status_code: msg: bytes = STATUS_CODES.get(status_code, b"") message = msg.decode("utf8") @@ -86,6 +87,7 @@ def __init__( self.status_code = status_code or self.status_code self.quiet = quiet self.headers = headers + self.message = message class HTTPException(SanicException): diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 29c4e45c8f..ebcda8f9bc 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -398,3 +398,16 @@ def test_exception_aliases(): assert MethodNotSupported is MethodNotAllowed assert ContentRangeError is RangeNotSatisfiable assert HeaderExpectationFailed is ExpectationFailed + + +def test_exception_message_attribute(): + assert ServerError("it failed").message == "it failed" + assert ServerError(b"it failed").message == b"it failed" + assert ServerError().message == str(ServerError()) == "Internal Server Error" + + class CustomError(SanicException): + message = "Something bad happened" + + assert CustomError().message == CustomError.message == str(CustomError()) + assert SanicException().message != "" + assert SanicException("").message == ""