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

Make the .message field on exceptions non-empty #2947

Merged
merged 8 commits into from
Jun 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(
quiet: Optional[bool] = None,
context: Optional[Dict[str, Any]] = None,
extra: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
) -> None:
self.context = context
self.extra = extra
Expand All @@ -75,17 +75,22 @@ 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
elif status_code:
msg: bytes = STATUS_CODES.get(status_code, b"")
message = msg.decode("utf8")
message = self.message
if not message and status_code:
msg = STATUS_CODES.get(status_code, b"")
message = msg.decode()
elif isinstance(message, bytes):
message = message.decode()

super().__init__(message)

self.status_code = status_code or self.status_code
self.quiet = quiet
self.headers = headers
try:
self.message = message
except AttributeError:
...


class HTTPException(SanicException):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,18 @@ 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 == "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 == ""
Loading