python runtime_error ai_generated true

fastapi.exceptions.HTTPException: 404 Not Found

ID: python/fastapi-http-exception-handling

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 95% success Raise HTTPException with appropriate status code and message
    from fastapi import HTTPException
    raise HTTPException(status_code=404, detail="Item not found")
  2. 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:

  1. Returning a generic error message without raising HTTPException 70% fail

    Does not properly signal the error to the client; may cause confusion.

  2. Catching the exception and returning a 200 status 85% fail

    Misrepresents the error; client thinks the request succeeded.