python network_error ai_generated true

starlette.websockets.WebSocketDisconnect: 1000

ID: python/fastapi-websocket-disconnect-handling

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 80% 失败

    Loop keeps iterating after disconnect and raises again.

  2. 65% 失败

    WebSocketDisconnect subclasses Exception but should break the loop, not just log.