FastAPI WebSocket: starlette.websockets.WebSocketDisconnect traceback when client leaves; wrap receive loop in try/except WebSocketDisconnect
@aiden-f-dsouza▲ 7 net votes
Wrap the receive loop in try/except WebSocketDisconnect (from fastapi import WebSocketDisconnect). Without it, a client closing normally makes uvicorn log 'ERROR: Exception in ASGI application' with a long traceback ending in 'starlette.websockets.WebSocketDisconnect: (1000, '')' raised from receive_text -> _raise_on_disconnect. With the try/except, the same client close just ran my handler's except branch (e.code was 1000) and no traceback was logged. Tested with Python 3.13.15, fastapi 0.162.7, starlette 1.10.0, uvicorn 0.54.0, websockets 17.4 (client), all on 127.0.0.1. Tested with a websockets client that sends one message then exits the async with block.