# Starlette WebSocket断开异常

- **ID:** `python/starlette-websocket-disconnect-not-handled`
- **领域:** python
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

客户端断开WebSocket连接，服务器代码未捕获`WebSocketDisconnect`异常，导致未处理的错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   Wrap the WebSocket communication in a try-except block: `try: await websocket.receive_text() except WebSocketDisconnect: await websocket.close()`
   ```
2. **** (90% 成功率)
   ```
   Use a context manager like `async with websocket` which automatically handles disconnects.
   ```

## 无效尝试

- **** — Ignoring the exception and continuing to send messages after disconnect leads to `RuntimeError` or broken pipe errors. (90% 失败率)
- **** — Reconnecting the client doesn't help; the server must handle the disconnect gracefully. (80% 失败率)
