在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中文网其他相关文章!