怎样统一 FastAPI 默认 HTTP 异常的返回结构?
查看完整题解
参考回答
直接回答
可以为 Starlette 的 HTTPException 注册处理器,使路由层错误和框架抛出的同类异常进入统一处理。处理器应保留状态码和必要响应头。
讲清原理
校验错误使用不同的异常类。它们可以按自己的契约处理。不要把所有异常改成 200,也不能丢掉认证或限速所需的头。
例子与易错点
示例把找不到的路径与需要认证的情形用同一错误结构返回,保留 404、401 以及认证响应头。
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from starlette.exceptions import HTTPException as StarletteHTTPException
app = FastAPI()
@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, error: StarletteHTTPException):
return JSONResponse(status_code=error.status_code, headers=error.headers,
content={"error": error.detail})
@app.get("/private")
def private():
raise HTTPException(status_code=401, detail="login required",
headers={"WWW-Authenticate": "Bearer"})
with TestClient(app) as client:
assert client.get("/missing").json() == {"error": "Not Found"}
denied = client.get("/private")
assert denied.status_code == 401 and denied.json() == {"error": "login required"}
assert denied.headers["WWW-Authenticate"] == "Bearer"
print(denied.status_code, denied.headers["WWW-Authenticate"])
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。