Fixing CancelledError When FastAPI SSE Clients Disconnect
Β· 2 min read
Encountered this while building an AI customer-service automation system for a client β recording the root cause and fix.
TL;DRβ
FastAPI's StreamingResponse cancels the generator task when the client disconnects, raising asyncio.CancelledError. The correct fix is to catch the exception inside the generator and re-raise β otherwise you get error-log noise and resource leaks.