{
  "id": "python/starlette-middleware-order-matters",
  "signature": "RuntimeError: Cannot add middleware after an application has started",
  "signature_zh": "RuntimeError: 应用启动后无法再添加中间件",
  "regex": "RuntimeError:\\ Cannot\\ add\\ middleware\\ after\\ an\\ application\\ has\\ started",
  "domain": "python",
  "category": "config_error",
  "subcategory": null,
  "root_cause": "Calling app.add_middleware() after the ASGI application has begun serving requests (e.g. inside a request handler).",
  "root_cause_type": "generic",
  "root_cause_zh": "在ASGI应用开始处理请求后（例如在请求处理函数内部）调用app.add_middleware()。",
  "versions": [
    {
      "version": "0.30.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "0.36.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Startup events run after middleware stack is built.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "Existing routes and state are lost.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.97,
      "how": "app = FastAPI()\\napp.add_middleware(CORSMiddleware, allow_origins=['*'])",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "app = MyMiddleware(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.87,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-07-11",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}