python
network_error
ai_generated
true
starlette.websockets.WebSocketDisconnect: 1000
ID: python/fastapi-websocket-disconnect-handling
80%修复率
86%置信度
0证据数
2024-07-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
客户端关闭了 WebSocket;处理函数继续调用 receive/send 且未捕获断开异常,导致异常向上传播。
English
Client closed the WebSocket; the handler keeps calling receive/send without catching the disconnect, propagating the exception.
解决方案
-
93% 成功率
Catch and break: try: while True: data = await ws.receive_text() except WebSocketDisconnect: pass -
85% 成功率
Use ws.iter_text() which stops on disconnect.
无效尝试
常见但无效的做法:
-
80% 失败
Loop keeps iterating after disconnect and raises again.
-
65% 失败
WebSocketDisconnect subclasses Exception but should break the loop, not just log.