FastAPI 错误处理
用可验证的响应区分默认 HTTP 异常、自定义异常、请求校验、重定向与直接 JSON。
学完这一章,你能够
- 用可验证的响应区分默认 HTTP 异常、自定义异常、请求校验、重定向与直接 JSON。
用 raise 结束当前请求分支
当记录缺失,raise HTTPException(404, 'locker missing') 将控制交给框架的异常处理器。正常分支返回记录;异常分支会返回实际 HTTP 404 和 detail。HTTPException 实例应抛出,直接 return 会作为返回值处理。
detail 可传字符串、可 JSON 序列化的字典或列表。本站 /default-errors/locker/bad 返回机器可读的错误代码与提示,/multiple 返回列表。序列化复杂 Python 对象前应先转换,避免在错误处理阶段再次出错。
headers 用于传递独立响应字段。本站 404 携带 X-Lab-Error,实验限流分支返回 429 和 Retry-After: 3。该分支固定返回教学状态,未实现实际限流。
把领域错误和输入校验分开
领域冲突可定义为 ReservationConflict,在 @app.exception_handler 中转成结构化 JSON 和 409。成功编号走正常返回。处理器可按异常类型处理一致的业务语义。
用 StarletteHTTPException 注册能同时处理 FastAPI 抛出的 HTTPException 和路由未匹配等框架错误。重写处理器时要保留 exc.status_code 和必要的 exc.headers。本站 401 仍提供 WWW-Authenticate,未匹配路径仍是 404。
RequestValidationError 表示请求输入不能按契约绑定。本站将 loc、type 和 msg 转成 422 错误详情,不返回整段原始请求或错误上下文。服务端响应模型错误另属服务端故障,不能按请求输入错误一并处理。
重定向和自定义响应
RedirectResponse 默认返回 307 和 Location。禁用自动跟随可先检查这一跳,再向目标发请求。本站跟随 307 的 POST 观察到原方法和 JSON 请求体被保留。选择 303 等其它状态时,客户端行为会不同。
JSONResponse 可以直接声明 JSON 内容、HTTP 状态和额外字段。/errors/accepted 返回 202、X-Lab-Result 和小 JSON 对象。直接返回响应对象时,应自行保证发送内容符合契约。
HTTPException 的输入
| 参数 | 类型 | 用途 |
|---|---|---|
| status_code | int | 指定实际 HTTP 状态。 |
| detail | Any | FastAPI 默认错误正文中的可 JSON 序列化信息。 |
| headers | dict[str, str] | None | 携带认证挑战、重试时间或其它额外响应字段。 |
记录错误、处理器和请求重定向
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
default=FastAPI()
handled=FastAPI()
@default.get("/locker/{code}")
def locker(code: str):
if code == "bad":
raise HTTPException(400, {"code":"BAD_LOCKER", "hint":"use the assigned code"})
if code == "multiple":
raise HTTPException(400, ["first", "second"])
if code == "busy":
raise HTTPException(429, "please wait", headers={"Retry-After":"3"})
if code != "A7":
raise HTTPException(404, "locker missing", headers={"X-Lab-Error":"missing"})
return {"locker":code}
class ReservationConflict(Exception):
def __init__(self, slot):
self.slot=slot
@handled.exception_handler(ReservationConflict)
async def conflict(_request: Request, error: ReservationConflict):
return JSONResponse({"error":"reservation_conflict","slot":error.slot},status_code=409)
@handled.exception_handler(StarletteHTTPException)
async def http_error(_request: Request, error: StarletteHTTPException):
return JSONResponse({"error":"http","detail":error.detail},status_code=error.status_code,headers=error.headers)
@handled.exception_handler(RequestValidationError)
async def invalid(_request: Request, error: RequestValidationError):
issues=[{"loc":list(item["loc"]),"type":item["type"],"msg":item["msg"]} for item in error.errors()]
return JSONResponse({"error":"validation","issues":issues},status_code=422)
@handled.get("/locker/{number}")
def lookup(number: int):
if number == 7:
raise ReservationConflict(number)
if number == 0:
raise HTTPException(401,"lab credential required",headers={"WWW-Authenticate":"Bearer"})
return {"locker":number}
@handled.get("/redirect")
def redirect():
return RedirectResponse(url="/errors/locker/8")
@handled.post("/redirect-method")
def preserve():
return RedirectResponse(url="/errors/echo")
@handled.post("/echo")
async def echo(request: Request):
return {"method":request.method,"received":await request.json()}
@handled.get("/accepted")
def accepted():
return JSONResponse({"queued":True},status_code=202,headers={"X-Lab-Result":"queued"})
- 正常请求、404、409 和 422 有各自响应。重写处理器仍保留认证头,307 会指向目标。
所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
当前源码 SHA256:364a4b7318f8035ea55407a440d3f20a24930b464dafdcf941843fe4b6624932
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
ZIP SHA256:4b423526f6738d401421a5696e073748452cadd78619b5bead2629f1f8f1859b
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
对 /errors/redirect-method 发送 JSON POST,分别关闭和开启自动跟随。
展开参考解答
关闭时看到 307 和 Location,开启时最终回显 POST 及同一 JSON。