剛做的網(wǎng)站怎么知道有沒有潛在的今日國際軍事新聞頭條
目錄
1 自定義參數(shù)校驗異常
2 自定義的curr_page_v參數(shù)校驗函數(shù),如果不合法拋出自定義異常!
3 配置全局異常
1 自定義參數(shù)校驗異常
# 1.用戶自定義異常類型,只要該類繼承了Exception類即可
class ValDtoError(Exception):# 初始化def __init__(self, message):self.message = message# 類一般返回值def __str__(self):return "參數(shù)校驗異常!" + self.message
2 自定義的curr_page_v參數(shù)校驗函數(shù),如果不合法拋出自定義異常!
Pydantic提供了四種validator :
BeforeValidator 運行在Pydantic內(nèi)部的校驗轉(zhuǎn)換之前,入?yún)檩斎胫礎ny,返回值為Any。
AfterValidator 運行在Pydantic內(nèi)部的校驗轉(zhuǎn)換之后,入?yún)⒑头祷刂禐檎_的字段類型。?
PlainValidator 運行時間和BeforeValidator相同,但執(zhí)行完之后整個校驗過程結(jié)束,不再執(zhí)行其他validator和Pydantic內(nèi)部的校驗流程。
?WrapValidator 可以運行在pydantic和其他validator之前或者之后,或者返回值、拋出異常立即結(jié)束校驗流程。
可以使用多個BeforeValidator、AfterValidator和WrapperValidator,但是只能有一個PlainValidator。關于執(zhí)行順序,從右到左執(zhí)行所有Before和Wrap校驗器,再從左到右執(zhí)行所有After校驗器
class CommonPageDto(BaseModel):def curr_page_v(v:int) -> int:if 111 > v:raise ValDtoError('開始頁不能小于0!')return vcurrPage: Annotated[int, BeforeValidator(curr_page_v)]pageSize: intsearch: dict
3 配置全局異常
@app.exception_handler(ValDtoError)
async def request_validation_exception_handler2(request: Request, exc: ValDtoError):print(f"參數(shù)校驗異常{request.method} {request.url}")print(exc)return fail_res(f"請求參數(shù)為{exc}")