python runtime_error ai_generated true

运行时错误:连接不存在。

RuntimeError: Connection does not exist.

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

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
0证据数
2024-07-22首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. Reusing WebSocket object after disconnect 80% 失败

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

  2. Assuming connection persists across requests 90% 失败

    Each WebSocket request creates a new connection object.