# FastAPI HTTP异常：404未找到

- **ID:** `python/fastapi-http-exception-handling`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Raise HTTPException with appropriate status code and message** (95% 成功率)
   ```
   from fastapi import HTTPException
raise HTTPException(status_code=404, detail="Item not found")
   ```
2. **Use exception handlers for custom responses** (90% 成功率)
   ```
   @app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})
   ```

## 无效尝试

- **Returning a generic error message without raising HTTPException** — Does not properly signal the error to the client; may cause confusion. (70% 失败率)
- **Catching the exception and returning a 200 status** — Misrepresents the error; client thinks the request succeeded. (85% 失败率)
