python runtime_error ai_generated true

RuntimeError: Connection does not exist.

ID: python/starlette-runtimeerror-connection-does-not-exist

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Attempting to use a WebSocket connection that has already been closed or was never established.

generic

中文

尝试使用已经关闭或从未建立的WebSocket连接。

Workarounds

  1. 85% success Check if WebSocket is connected before using
    if websocket.client_state == starlette.websockets.WebSocketState.CONNECTED:
        await websocket.send_text('hello')
  2. 90% success Handle disconnection with try-except
    try:
        await websocket.receive_text()
    except RuntimeError:
        # connection closed
        pass

Dead Ends

Common approaches that don't work:

  1. Reusing WebSocket object after disconnect 80% fail

    WebSocket connections are single-use; must accept new connections.

  2. Assuming connection persists across requests 90% fail

    Each WebSocket request creates a new connection object.