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
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.
解决方案
-
98% 成功率
raise HTTPException(status_code=404, detail='Not found')
-
90% 成功率
from fastapi.responses import JSONResponse return JSONResponse(status_code=404, content={'detail': 'Not found'})
无效尝试
常见但无效的做法:
-
85% 失败
Returns a 200 with exception internals in the body instead of an error status.
-
70% 失败
Leaks stack/details and still uses the wrong status code.