python
network_error
ai_generated
true
starlette.websockets.WebSocketDisconnect: 1000
ID: python/fastapi-websocket-disconnect-handling
80%Fix Rate
86%Confidence
0Evidence
2024-07-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Client closed the WebSocket; the handler keeps calling receive/send without catching the disconnect, propagating the exception.
generic中文
客户端关闭了 WebSocket;处理函数继续调用 receive/send 且未捕获断开异常,导致异常向上传播。
Workarounds
-
93% success
Catch and break: try: while True: data = await ws.receive_text() except WebSocketDisconnect: pass -
85% success
Use ws.iter_text() which stops on disconnect.
Dead Ends
Common approaches that don't work:
-
80% fail
Loop keeps iterating after disconnect and raises again.
-
65% fail
WebSocketDisconnect subclasses Exception but should break the loop, not just log.