python type_error ai_generated true

TypeError: HTTPException 类型的对象无法 JSON 序列化

TypeError: Object of type HTTPException is not JSON serializable

ID: python/fastapi-http-exception-detail-dict

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

版本兼容性

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

根因分析

路由将 HTTPException 对象返回或嵌入响应,而不是抛出它,导致 JSON 编码失败。

English

The route returns or embeds an HTTPException object in a response instead of raising it, so JSON encoding fails.

generic

解决方案

  1. 95% 成功率
    Raise it so FastAPI handles it:
    raise HTTPException(status_code=404, detail='not found')
  2. 85% 成功率
    Return a plain dict with the error shape you want.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Serializes the exception but returns 200 with error data instead of the proper status.

  2. 70% 失败

    Loses status code and structured detail.