在FastAPI中,當驗證要求時,如果參數遺失或無效, FastAPI引發RequestValidationError 異常。預設情況下,此異常會傳回 422 Unprocessable Entity 回應。但是,您可能希望針對特定路由自訂此回應。以下是實現此目的的幾種方法:
覆蓋RequestValidationError 的預設異常處理程序並為所需的內容提供自訂回應路線。
from fastapi import FastAPI, Request, status, HTTPException from fastapi.responses import JSONResponse from fastapi.encoders import jsonable_encoder from fastapi.exceptions import RequestValidationError app = FastAPI() routes_with_custom_exception = ['/'] @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): if request.url.path in routes_with_custom_exception: return JSONResponse(content={'401': 'Unauthorized'}, status_code=401)
建立一個子應用程式並將其掛載到特定路由的主應用程式。重寫子應用程式中 RequestValidationError 的異常處理程序。
from fastapi import FastAPI, RequestValidationError, HTTPException from fastapi.responses import JSONResponse app = FastAPI() subapi = FastAPI() @subapi.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) app.mount('/sub', subapi)
建立自訂 APIRoute 子類別並重寫get_route_handler 方法。這允許您攔截請求並處理 RequestValidationError 異常。
from fastapi import FastAPI from fastapi.routing import APIRoute from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from fastapi.requests import Request class ValidationErrorHandlingRoute(APIRoute): def get_route_handler(self): original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request): try: return await original_route_handler(request) except RequestValidationError as e: return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) return custom_route_handler app = FastAPI() router = APIRouter(route_class=ValidationErrorHandlingRoute) @app.get('/') async def main(): return {'message': 'Hello from main API'} @router.get('/custom') async def custom_route(some_custom_header: str = Header(...)): return {'some-custom-header': some_custom_header} app.include_router(router)
以上是如何自訂FastAPI針對特定路由的錯誤回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!