python
runtime_error
ai_generated
true
fastapi.exceptions.HTTPException: 404 Not Found
ID: python/fastapi-http-exception-handling
80%Fix Rate
84%Confidence
0Evidence
2024-08-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
The requested resource does not exist, and the code raises an HTTPException with status code 404.
generic中文
请求的资源不存在,代码抛出了状态码为404的HTTPException。
Workarounds
-
95% success Raise HTTPException with appropriate status code and message
from fastapi import HTTPException raise HTTPException(status_code=404, detail="Item not found")
-
90% success Use exception handlers for custom responses
@app.exception_handler(HTTPException) async def http_exception_handler(request, exc): return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})
Dead Ends
Common approaches that don't work:
-
Returning a generic error message without raising HTTPException
70% fail
Does not properly signal the error to the client; may cause confusion.
-
Catching the exception and returning a 200 status
85% fail
Misrepresents the error; client thinks the request succeeded.