python data_error ai_generated true

RuntimeError: Body is not JSON: 'invalid json'

ID: python/starlette-request-body-parsing-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-09-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

请求体包含无效的JSON格式,但Starlette尝试解析为JSON

generic

中文

请求体包含无效的JSON格式,但Starlette尝试解析为JSON

Workarounds

  1. 90% success 在路由中处理JSON解析异常
    from starlette.responses import JSONResponse
    async def endpoint(request):
        try:
            data = await request.json()
        except ValueError:
            return JSONResponse({'error': 'Invalid JSON'}, status_code=400)
  2. 85% success 使用中间件验证请求体格式
    from starlette.middleware.base import BaseHTTPMiddleware
    class JSONValidationMiddleware(BaseHTTPMiddleware):
        async def dispatch(self, request, call_next):
            if request.headers.get('content-type') == 'application/json':
                body = await request.body()
                import json
                try:
                    json.loads(body)
                except json.JSONDecodeError:
                    return JSONResponse({'error': 'Invalid JSON'}, status_code=400)
            return await call_next(request)

Dead Ends

Common approaches that don't work:

  1. 在请求中手动解析JSON 50% fail

    Starlette自动尝试解析JSON,手动解析会重复

  2. 忽略错误并返回空数据 40% fail

    异常在解析时抛出,无法继续处理