修复 FastAPI SSE 客户端断开时的 CancelledError
在为客户构建 AI 客服自动化系统时遇到此问题,记录根因与解法。
TL;DR
FastAPI 的 StreamingResponse 在客户端断开连接时会取消生成器任务,导致 asyncio.CancelledError。正确做法是在生成器中捕获该异常并 re-raise,否则会导致异常日志污染和资源泄漏。
在为客户构建 AI 客服自动化系统时遇到此问题,记录根因与解法。
FastAPI 的 StreamingResponse 在客户端断开连接时会取消生成器任务,导致 asyncio.CancelledError。正确做法是在生成器中捕获该异常并 re-raise,否则会导致异常日志污染和资源泄漏。
Key points for GA4 in React SPA: 1) Set send_page_view: false to prevent duplicate counts; 2) Use useLocation to track route changes and send pageviews manually; 3) Set user_id after login for cross-device tracking.
Pydantic v2 no longer supports class Config. Use model_config = ConfigDict(from_attributes=True) instead. If your model has a field named model_config, you must rename it to avoid conflict with the reserved attribute.
Vite path aliases require simultaneous configuration in both vite.config.ts and tsconfig.json—neither works alone. Vite handles bundler resolution, TypeScript handles type checking and IDE intellisense.
The key to cascade selection: when parent changes, reset child to a valid value. Use Record<string, Option[]> for type-safe data mapping, and update child state inside onValueChange callback.