Add default messages to SanicExceptions (#2216)

* Add default messages to SanicExceptions

* Cleaner exception message setting
This commit is contained in:
Adam Hopkins 2021-08-09 21:14:15 +03:00 committed by GitHub
parent 08c5689441
commit e1cfbf0fd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 4 deletions

View File

@ -4,14 +4,18 @@ from sanic.helpers import STATUS_CODES
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:
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")

View File

@ -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__)