Python?Fastapi實現(xiàn)統(tǒng)一處理各種異常
在 FastAPI 中處理參數(shù)校驗錯誤(通常由 Pydantic 模型或路徑參數(shù)校驗觸發(fā))需要使用自定義異常處理器捕獲 RequestValidationError
。以下是詳細實現(xiàn)步驟:
1. 基礎(chǔ)實現(xiàn)(返回標準錯誤結(jié)構(gòu))
from fastapi import FastAPI, Request, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={ "code": 422, "message": "參數(shù)校驗失敗", "errors": exc.errors() }, ) # 示例路由 @app.get("/items/{item_id}") async def read_item(item_id: int, q: str): return {"item_id": item_id, "q": q}
2. 自定義錯誤格式(簡化輸出)
@app.exception_handler(RequestValidationError) async def custom_validation_handler(request: Request, exc: RequestValidationError): simplified_errors = [] for error in exc.errors(): # 提取關(guān)鍵信息 simplified_errors.append({ "field": "->".join(str(loc) for loc in error["loc"]), # 錯誤字段路徑 "msg": error["msg"], "type": error["type"] }) return JSONResponse( status_code=422, content={ "error": "ValidationError", "detail": simplified_errors } )
3. 完整示例(含路由演示)
from pydantic import BaseModel, Field class Item(BaseModel): name: str = Field(..., min_length=3) price: float = Field(gt=0) @app.post("/items/") async def create_item(item: Item): return item # 測試無效請求 # curl -X POST 'http://localhost:8000/items/' \ # -H 'Content-Type: application/json' \ # -d '{"name": "AB", "price": -1}'
4. 處理自定義錯誤類型(擴展)
如果需要統(tǒng)一處理其他錯誤:
from fastapi import HTTPException @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={"error": exc.detail} )
關(guān)鍵說明
1.錯誤信息結(jié)構(gòu):
{ "loc": ["body", "price"], "msg": "ensure this value is greater than 0", "type": "value_error.number.not_gt" }
loc
:錯誤位置(body/query/path/header等 + 字段路徑)msg
:人類可讀錯誤描述type
:錯誤類型標識符
2.HTTP 狀態(tài)碼:
參數(shù)校驗錯誤通常返回 422 Unprocessable Entity
路徑參數(shù)錯誤(如 item_id: int
接收到字符串)會觸發(fā)相同錯誤
3.調(diào)試信息: 生產(chǎn)環(huán)境中建議隱藏詳細錯誤,可通過環(huán)境變量控制:
import os @app.exception_handler(RequestValidationError) async def handler(...): if os.getenv("ENV") == "prod": return JSONResponse(status_code=422, content={"error": "Invalid params"}) else: # 返回完整錯誤
測試驗證
使用無效參數(shù)請求示例路由,將得到類似響應(yīng):
{ "code": 422, "message": "參數(shù)校驗失敗", "errors": [ { "field": "body->name", "msg": "ensure this value has at least 3 characters", "type": "value_error.any_str.min_length" }, { "field": "body->price", "msg": "ensure this value is greater than 0", "type": "value_error.number.not_gt" } ] }
提示:FastAPI 自動生成的文檔(Swagger UI)中的參數(shù)校驗錯誤由內(nèi)置處理器處理,自定義處理器不影響文檔界面行為。
到此這篇關(guān)于Python Fastapi實現(xiàn)統(tǒng)一處理各種異常的文章就介紹到這了,更多相關(guān)Python Fastapi異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
CoAtNet實戰(zhàn)之對植物幼苗圖像進行分類(pytorch)
谷歌的最新模型CoAtNet做了卷積 + Transformer的融合,在ImageNet-1K數(shù)據(jù)集上取得88.56%的成績。本文主要介紹如何用CoAtNet實現(xiàn)植物幼苗圖像的分類。感興趣的小伙伴可以學習一下2021-12-12Scrapy項目實戰(zhàn)之爬取某社區(qū)用戶詳情
這篇文章主要介紹了Scrapy項目實戰(zhàn)之爬取某社區(qū)用戶詳情,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09Python面向?qū)ο蟪绦蛟O(shè)計之私有變量,私有方法原理與用法分析
這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計之私有變量,私有方法,結(jié)合實例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計中私有變量,私有方法相關(guān)概念、原理、用法及操作注意事項,需要的朋友可以參考下2020-03-03pip安裝提示Twisted錯誤問題(Python3.6.4安裝Twisted錯誤)
這篇文章主要介紹了pip安裝提示Twisted錯誤問題(Python3.6.4安裝Twisted錯誤),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05matplotlib圖例、標簽、坐標軸刻度的字體設(shè)置方式
這篇文章主要介紹了matplotlib圖例、標簽、坐標軸刻度的字體設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05