python type_error ai_generated true

TypeError: ValueError 类型的对象不可 JSON 序列化

TypeError: Object of type ValueError is not JSON serializable

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-10-30首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

    Loses error context and clients get an empty body.

  2. 80% 失败

    Leaks internals and is fragile across exception types.