# starlette.websockets.WebSocketDisconnect: 1000

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

## 根因

客户端关闭了 WebSocket；处理函数继续调用 receive/send 且未捕获断开异常，导致异常向上传播。

## 版本兼容性

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

## 解决方案

1. **** (93% 成功率)
   ```
   Catch and break:
try:
    while True:
        data = await ws.receive_text()
except WebSocketDisconnect:
    pass
   ```
2. **** (85% 成功率)
   ```
   Use ws.iter_text() which stops on disconnect.
   ```

## 无效尝试

- **** — Loop keeps iterating after disconnect and raises again. (80% 失败率)
- **** — WebSocketDisconnect subclasses Exception but should break the loop, not just log. (65% 失败率)
