{
  "id": "python/starlette-middleware-order-response-headers",
  "signature": "AssertionError: Cannot add middleware after an application has started",
  "signature_zh": "AssertionError: 应用启动后无法添加中间件",
  "regex": "AssertionError:\\ Cannot\\ add\\ middleware\\ after\\ an\\ application\\ has\\ started",
  "domain": "python",
  "category": "config_error",
  "subcategory": null,
  "root_cause": "app.add_middleware() was called after the ASGI app had already started serving (e.g., inside a route or after TestClient instantiation).",
  "root_cause_type": "generic",
  "root_cause_zh": "在 ASGI 应用已经开始提供服务后调用了 app.add_middleware()（例如在路由内或 TestClient 实例化之后）。",
  "versions": [
    {
      "version": "0.30+",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "The middleware is never added; headers/logging silently missing.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Startup fires after the middleware stack is built; assertion still raised.",
      "fail_rate": 0.9,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.95,
      "how": "app = FastAPI()\napp.add_middleware(CORSMiddleware, allow_origins=['*'])\n# then define routes",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "def create_app():\n    app = FastAPI()\n    app.add_middleware(...)\n    return app",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.84,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-08-27",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}