python network_error ai_generated true

starlette.websockets.WebSocketDisconnect: 1000

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 80% fail

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