python network_error ai_generated true

Starlette WebSocket断开异常

starlette.websockets.WebSocketDisconnect: 1000

ID: python/starlette-websocket-disconnect-not-handled

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

版本兼容性

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

根因分析

客户端断开WebSocket连接,服务器代码未捕获`WebSocketDisconnect`异常,导致未处理的错误。

English

Client disconnects from a WebSocket connection, and the server code doesn't catch the `WebSocketDisconnect` exception, causing an unhandled error.

generic

解决方案

  1. 95% 成功率
    Wrap the WebSocket communication in a try-except block: `try: await websocket.receive_text() except WebSocketDisconnect: await websocket.close()`
  2. 90% 成功率
    Use a context manager like `async with websocket` which automatically handles disconnects.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Ignoring the exception and continuing to send messages after disconnect leads to `RuntimeError` or broken pipe errors.

  2. 80% 失败

    Reconnecting the client doesn't help; the server must handle the disconnect gracefully.