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

Add default messages to SanicExceptions #2216

Merged
merged 9 commits into from
Aug 9, 2021
12 changes: 8 additions & 4 deletions sanic/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
16 changes: 16 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down