python type_error ai_generated true

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

TypeError: Object of type HTTPException is not JSON serializable

ID: python/fastapi-http-exception-not-json

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

版本兼容性

版本状态引入弃用备注
0.100+ active — — —

根因分析

路由返回了 HTTPException 实例而不是抛出它,导致 FastAPI 尝试将异常对象序列化为响应正文。

English

A route returned an HTTPException instance instead of raising it, so FastAPI tried to serialize the exception object as the response body.

generic

解决方案

  1. 98% 成功率
    raise HTTPException(status_code=404, detail='Not found')
  2. 90% 成功率
    from fastapi.responses import JSONResponse
    return JSONResponse(status_code=404, content={'detail': 'Not found'})

无效尝试

常见但无效的做法:

  1. 85% 失败

    Returns a 200 with exception internals in the body instead of an error status.

  2. 70% 失败

    Leaks stack/details and still uses the wrong status code.