错误处理

FastAPI 入门

Matt Eckerle

Software and Data Leader

处理错误的两大原因

用户错误

  • URI 无效或已过期
  • 输入缺失或不正确
@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # 返回错误
    else:
        crud.delete_item(item)
        return {}

服务器错误

  • 发生了其他问题
@app.delete("/items")
def delete_item(item: Item):
    try:
        crud.delete_item(item)
    except Exception:
        # 返回错误
    return {}
FastAPI 入门

HTTP 状态码:不同“严重度”

  • 使 API 在响应中表达状态
    • 成功、失败、错误等
  • HTTP 协议定义了具体代码
  • 范围:100 - 599
  • 按首位数字分组(1 -5
  1. 信息性响应(100 - 199
  2. 成功响应(200 - 299
  3. 重定向(300 - 399
  4. 客户端错误(400 - 499
  5. 服务器错误(500 - 599
1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
FastAPI 入门

常见 HTTP 状态码

成功(200 - 299

  • 200 OK
    • 默认成功响应
  • 201 Created
    • 专用于 POST 操作
  • 202 Accepted
    • 暂不承诺,"处理中"
  • 204 No Content
    • 成功!无返回内容

其他响应

  • 301 Moved Permantently
    • URI 永久变更
  • 400 Bad Request
    • 客户端错误
  • 404 Not Found
    • 服务器找不到请求的资源
  • 500 Internal Server Error
    • 服务器遇到无法处理的情况
FastAPI 入门

用状态码处理错误

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        # 发送状态码 404 和具体错误信息的响应
        raise HTTPException(status_code=404, detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}
FastAPI 入门

Passons à la pratique !

FastAPI 入门

Preparing Video For Download...