python type_error ai_generated true

TypeError: Object of type ValueError is not JSON serializable

ID: python/fastapi-http-exception-detail-not-serializable

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-10-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

HTTPException detail was passed a non-serializable object (e.g. an exception) instead of a string or dict.

generic

中文

HTTPException 的 detail 传入了不可序列化的对象(如异常实例),而不是字符串或字典。

Workarounds

  1. 95% success
    raise HTTPException(status_code=400, detail=str(e))
  2. 90% success
    raise HTTPException(400, detail={'error': 'bad_input', 'message': str(e)})

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Loses error context and clients get an empty body.

  2. 80% fail

    Leaks internals and is fragile across exception types.