{
  "id": "python/starlette-request-body-parsing-error",
  "signature": "RuntimeError: Body is not JSON: 'invalid json'",
  "signature_zh": "运行时错误：请求体不是JSON：'invalid json'",
  "regex": "RuntimeError:\\ Body\\ is\\ not\\ JSON:\\ 'invalid\\ json'",
  "domain": "python",
  "category": "data_error",
  "subcategory": null,
  "root_cause": "请求体包含无效的JSON格式，但Starlette尝试解析为JSON",
  "root_cause_type": "generic",
  "root_cause_zh": "请求体包含无效的JSON格式，但Starlette尝试解析为JSON",
  "versions": [
    {
      "version": "3.x",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "在请求中手动解析JSON",
      "why_fails": "Starlette自动尝试解析JSON，手动解析会重复",
      "fail_rate": 0.5,
      "condition": "",
      "sources": []
    },
    {
      "action": "忽略错误并返回空数据",
      "why_fails": "异常在解析时抛出，无法继续处理",
      "fail_rate": 0.4,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "在路由中处理JSON解析异常",
      "success_rate": 0.9,
      "how": "from starlette.responses import JSONResponse\nasync def endpoint(request):\n    try:\n        data = await request.json()\n    except ValueError:\n        return JSONResponse({'error': 'Invalid JSON'}, status_code=400)",
      "condition": "",
      "sources": []
    },
    {
      "action": "使用中间件验证请求体格式",
      "success_rate": 0.85,
      "how": "from starlette.middleware.base import BaseHTTPMiddleware\nclass JSONValidationMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request, call_next):\n        if request.headers.get('content-type') == 'application/json':\n            body = await request.body()\n            import json\n            try:\n                json.loads(body)\n            except json.JSONDecodeError:\n                return JSONResponse({'error': 'Invalid JSON'}, status_code=400)\n        return await call_next(request)",
      "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-09-18",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}