FastAPI 错误处理完全指南:从基础到高级实践

FastAPI 错误处理完全指南:从基础到高级实践

fastapi FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi 项目地址: https://gitcode.com/gh_mirrors/fa/fastapi

错误处理的重要性

在构建 API 时,错误处理是确保良好用户体验的关键环节。FastAPI 提供了强大而灵活的错误处理机制,让开发者能够清晰地告知客户端发生了什么问题。

HTTP 状态码基础

HTTP 协议定义了一系列状态码,用于表示请求的处理结果:

  • 2xx 系列:成功状态码(如 200 OK)
  • 4xx 系列:客户端错误(如 404 Not Found)
  • 5xx 系列:服务器错误(如 500 Internal Server Error)

在 FastAPI 中,我们主要关注 4xx 系列错误,用于告知客户端其请求存在问题。

基本错误处理:HTTPException

基本用法

FastAPI 提供了 HTTPException 类来处理常见的错误场景:

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id == "foo":
        return {"item": "The Foo Wrestlers"}
    raise HTTPException(status_code=404, detail="Item not found")

当客户端请求不存在的资源时,将收到:

{
  "detail": "Item not found"
}

高级特性

  1. 自定义错误详情detail 参数不仅接受字符串,还可以是字典、列表等任何可 JSON 序列化的对象
  2. 添加自定义头信息:某些安全场景可能需要额外的头信息
raise HTTPException(
    status_code=404,
    detail="Item not found",
    headers={"X-Error": "There goes my error"}
)

自定义异常处理器

对于特定业务异常,我们可以创建自定义处理器:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name

app = FastAPI()

@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}
    )

@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}

覆盖默认异常处理器

FastAPI 允许我们覆盖默认的异常处理行为。

请求验证错误

当请求数据无效时,FastAPI 会抛出 RequestValidationError

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)

HTTPException 处理器

同样可以覆盖默认的 HTTPException 处理:

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

高级技巧

访问验证错误的原始数据

开发时可能需要查看客户端发送的原始数据:

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=422,
        content={"detail": exc.errors(), "body": exc.body},
    )

复用 FastAPI 默认处理器

在自定义处理中复用默认行为:

from fastapi.exception_handlers import (
    http_exception_handler,
    request_validation_exception_handler,
)

@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
    print(f"OMG! An HTTP error!: {repr(exc)}")
    return await http_exception_handler(request, exc)

最佳实践建议

  1. 一致性:保持错误响应格式在整个 API 中一致
  2. 安全性:生产环境中避免返回过多错误细节
  3. 日志记录:重要错误应记录日志以便排查
  4. 用户友好:错误信息应当对 API 使用者有帮助

通过合理利用 FastAPI 的错误处理机制,可以构建出既健壮又用户友好的 API 服务。

fastapi FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi 项目地址: https://gitcode.com/gh_mirrors/fa/fastapi

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏纲墩Dean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值