python
type_error
ai_generated
true
TypeError: Object of type HTTPException is not JSON serializable
ID: python/fastapi-http-exception-not-json
80%Fix Rate
88%Confidence
0Evidence
2024-05-04First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.100+ | active | — | — | — |
Root Cause
A route returned an HTTPException instance instead of raising it, so FastAPI tried to serialize the exception object as the response body.
generic中文
路由返回了 HTTPException 实例而不是抛出它,导致 FastAPI 尝试将异常对象序列化为响应正文。
Workarounds
-
98% success
raise HTTPException(status_code=404, detail='Not found')
-
90% success
from fastapi.responses import JSONResponse return JSONResponse(status_code=404, content={'detail': 'Not found'})
Dead Ends
Common approaches that don't work:
-
85% fail
Returns a 200 with exception internals in the body instead of an error status.
-
70% fail
Leaks stack/details and still uses the wrong status code.