Skip to content

Commit

Permalink
Add reason to WebSocketException
Browse files Browse the repository at this point in the history
  • Loading branch information
Kludex committed May 10, 2022
1 parent 48469a8 commit 41b06d2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
7 changes: 4 additions & 3 deletions starlette/exceptions.py
Expand Up @@ -28,12 +28,13 @@ def __repr__(self) -> str:


class WebSocketException(Exception):
def __init__(self, code: int) -> None:
def __init__(self, code: int, reason: typing.Optional[str] = None) -> None:
self.code = code
self.reason = reason or ""

def __repr__(self) -> str:
class_name = self.__class__.__name__
return f"{class_name}(code={self.code!r})"
return f"{class_name}(code={self.code!r}, reason={self.reason!r})"


class ExceptionMiddleware:
Expand Down Expand Up @@ -133,4 +134,4 @@ def http_exception(self, request: Request, exc: HTTPException) -> Response:
async def websocket_exception(
self, websocket: WebSocket, exc: WebSocketException
) -> None:
await websocket.close(code=exc.code)
await websocket.close(code=exc.code, reason=exc.reason)
9 changes: 7 additions & 2 deletions tests/test_exceptions.py
Expand Up @@ -133,9 +133,14 @@ class CustomHTTPException(HTTPException):


def test_websocket_repr():
assert repr(WebSocketException(1008)) == ("WebSocketException(code=1008)")
assert repr(WebSocketException(1008, reason="Policy Violation")) == (
"WebSocketException(code=1008, reason='Policy Violation')"
)

class CustomWebSocketException(WebSocketException):
pass

assert repr(CustomWebSocketException(1013)) == "CustomWebSocketException(code=1013)"
assert (
repr(CustomWebSocketException(1013, reason="Something custom"))
== "CustomWebSocketException(code=1013, reason='Something custom')"
)

0 comments on commit 41b06d2

Please sign in to comment.