python
network_error
ai_generated
true
Starlette WebSocket断开异常
starlette.websockets.WebSocketDisconnect: 1000
ID: python/starlette-websocket-disconnect-not-handled
80%修复率
82%置信度
0证据数
2024-04-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
客户端断开WebSocket连接,服务器代码未捕获`WebSocketDisconnect`异常,导致未处理的错误。
English
Client disconnects from a WebSocket connection, and the server code doesn't catch the `WebSocketDisconnect` exception, causing an unhandled error.
解决方案
-
95% 成功率
Wrap the WebSocket communication in a try-except block: `try: await websocket.receive_text() except WebSocketDisconnect: await websocket.close()`
-
90% 成功率
Use a context manager like `async with websocket` which automatically handles disconnects.
无效尝试
常见但无效的做法:
-
90% 失败
Ignoring the exception and continuing to send messages after disconnect leads to `RuntimeError` or broken pipe errors.
-
80% 失败
Reconnecting the client doesn't help; the server must handle the disconnect gracefully.