WebSocketException Class — fastapi Architecture
Architecture documentation for the WebSocketException class in exceptions.py from the fastapi codebase.
Entity Profile
Dependency Diagram
graph TD 0c1f2a3d_8fb3_739d_0a29_b0255469b4ae["WebSocketException"] 01c652c5_d85c_f45e_848e_412c94ea4172["exceptions.py"] 0c1f2a3d_8fb3_739d_0a29_b0255469b4ae -->|defined in| 01c652c5_d85c_f45e_848e_412c94ea4172 f104fef5_a6a9_3a65_eac1_ce569beb7c17["__init__()"] 0c1f2a3d_8fb3_739d_0a29_b0255469b4ae -->|method| f104fef5_a6a9_3a65_eac1_ce569beb7c17
Relationship Graph
Source Code
fastapi/exceptions.py lines 86–154
class WebSocketException(StarletteWebSocketException):
"""
A WebSocket exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
## Example
```python
from typing import Annotated
from fastapi import (
Cookie,
FastAPI,
WebSocket,
WebSocketException,
status,
)
app = FastAPI()
@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
*,
websocket: WebSocket,
session: Annotated[str | None, Cookie()] = None,
item_id: str,
):
if session is None:
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Session cookie is: {session}")
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
```
"""
def __init__(
self,
code: Annotated[
int,
Doc(
"""
A closing code from the
[valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
"""
),
],
reason: Annotated[
Union[str, None],
Doc(
"""
The reason to close the WebSocket connection.
It is UTF-8-encoded data. The interpretation of the reason is up to the
application, it is not specified by the WebSocket specification.
It could contain text that could be human-readable or interpretable
by the client code, etc.
"""
),
] = None,
) -> None:
super().__init__(code=code, reason=reason)
Domain
Defined In
Source
Frequently Asked Questions
What is the WebSocketException class?
WebSocketException is a class in the fastapi codebase, defined in fastapi/exceptions.py.
Where is WebSocketException defined?
WebSocketException is defined in fastapi/exceptions.py at line 86.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free