第 4 章: 错误和状态码


本章概述

在本章中,我们将学习: - HTTP状态码 - 自定义方法中的响应状态码 - 错误处理 - 什么是HTTP异常? - 评估索引是否超出范围 - 评估任务是否未注册


4.1 HTTP状态码

HTTP状态码表示API请求的结果。常见的状态码包括:

  • 200 OK: 请求成功
  • 201 Created: 资源创建成功
  • 400 Bad Request: 客户端请求错误
  • 404 Not Found: 资源未找到
  • 422 Unprocessable Entity: 验证错误
  • 500 Internal Server Error: 服务器内部错误

4.2 自定义响应状态码

默认情况下,FastAPI返回200状态码。我们可以自定义:

from fastapi import FastAPI, status

app = FastAPI()

@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item():
    return {"message": "Item created"}

4.3 错误处理

什么是HTTP异常?

HTTPException是FastAPI提供的错误处理方式:

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}

@app.get("/items/{item_id}")
def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(
            status_code=404, 
            detail="Item not found"
        )
    return {"item": items[item_id]}

4.4 评估索引是否超出范围

@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id >= len(items):
        raise HTTPException(
            status_code=400, 
            detail="Index out of range"
        )
    return items[item_id]

4.5 评估任务是否未注册

@app.post("/tasks/")
def create_task(task: Task):
    if task.name in task_list:
        raise HTTPException(
            status_code=400, 
            detail=f"Task {task.name} already exists"
        )
    task_list.append(task)
    return task

4.6 自定义异常处理器

你可以自定义异常处理:

from fastapi import Request
from fastapi.responses import JSONResponse

@app.exception_handler(ValueError)
async def value_error_exception_handler(request: Request, exc: ValueError):
    return JSONResponse(
        status_code=400,
        content={"message": str(exc)},
    )

错误处理示例

小结

在本章中,我们学习了: - ✅ 理解HTTP状态码 - ✅ 自定义响应状态码 - ✅ 使用HTTPException处理错误 - ✅ 评估各种错误情况 - ✅ 自定义异常处理器

在下一章中,我们将学习如何声明示例数据!