{
  "id": "python/starlette-middleware-response-already-started",
  "signature": "RuntimeError: Unable to set headers after the response has started",
  "signature_zh": "RuntimeError: 响应已开始，无法设置头。",
  "regex": "RuntimeError:\\ Unable\\ to\\ set\\ headers\\ after\\ the\\ response\\ has\\ started",
  "domain": "python",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "A middleware tries to mutate headers after `await send(message)` has already sent `http.response.start`.",
  "root_cause_type": "generic",
  "root_cause_zh": "中间件在 `await send(message)` 已发送 `http.response.start` 后尝试修改头。",
  "versions": [
    {
      "version": "0.30+",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "",
      "why_fails": "Headers are silently missing; client sees wrong behavior.",
      "fail_rate": 0.85,
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "why_fails": "State flag doesn't alter ASGI message ordering.",
      "fail_rate": 0.95,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "",
      "success_rate": 0.95,
      "how": "async def __call__(self, scope, receive, send):\n    async def send_wrapper(message):\n        if message['type'] == 'http.response.start':\n            message['headers'].append((b'x-custom', b'1'))\n        await send(message)\n    await self.app(scope, receive, send_wrapper)",
      "condition": "",
      "sources": []
    },
    {
      "action": "",
      "success_rate": 0.9,
      "how": "from starlette.middleware.base import BaseHTTPMiddleware\nclass M(BaseHTTPMiddleware):\n    async def dispatch(self, request, call_next):\n        resp = await call_next(request)\n        resp.headers['x-custom'] = '1'\n        return resp",
      "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-10-05",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}