python network_error ai_generated true

starlette.websockets.WebSocketDisconnect: 1000

ID: python/fastapi-websocket-disconnect-handling

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Client closed the WebSocket; the handler keeps calling receive/send without catching the disconnect, propagating the exception.

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Loop keeps iterating after disconnect and raises again.

  2. 65% fail

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