python type_error ai_generated true

TypeError: Object of type HTTPException is not JSON serializable

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 75% fail

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

  2. 70% fail

    Loses status code and structured detail.