python runtime_error ai_generated true

FastAPI HTTP异常:404未找到

fastapi.exceptions.HTTPException: 404 Not Found

ID: python/fastapi-http-exception-handling

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

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

请求的资源不存在,代码抛出了状态码为404的HTTPException。

English

The requested resource does not exist, and the code raises an HTTPException with status code 404.

generic

解决方案

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

无效尝试

常见但无效的做法:

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

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

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

    Misrepresents the error; client thinks the request succeeded.