Skip to content

Commit

Permalink
Make the .message field on exceptions non-empty
Browse files Browse the repository at this point in the history
This allows subclasses of SanicException to access their message via the `message` attribute. This makes it consistent with the `status_code`, `quiet`, `headers` attributes that were previously present on the class.

Currently, the message attribute is present on the class but not on the instance, so accessing SanicException().message will return an empty string "" instead of the actual message "Internal Server Error", which you can get by calling the __str__() method or str().

This is a bit surprising, since the .message attribute shows up in autocomplete and type-checking. It also happens for the other exceptions, like str(BadRequest()) == "" as well.

I set the message attribute on instances of SanicException and added tests for this new behavior.
  • Loading branch information
ekzhang committed May 6, 2024
1 parent f8e0a72 commit 464fedb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == ""

0 comments on commit 464fedb

Please sign in to comment.