Add default messages to SanicExceptions (#2216)
* Add default messages to SanicExceptions * Cleaner exception message setting
This commit is contained in:
parent
08c5689441
commit
e1cfbf0fd9
|
@ -4,16 +4,20 @@ 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:
|
||||
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)
|
||||
|
||||
|
|
|
@ -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__)
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user