在 fastapi 中处理参数校验错误(通常由 pydantic 模型或路径参数校验触发)需要使用自定义异常处理器捕获 requestvalidationerror
。以下是详细实现步骤:
1. 基础实现(返回标准错误结构)
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": "参数校验失败", "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(): # 提取关键信息 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. 处理自定义错误类型(扩展)
如果需要统一处理其他错误:
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} )
关键说明
1.错误信息结构:
{ "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 状态码:
参数校验错误通常返回 422 unprocessable entity
路径参数错误(如 item_id: int
接收到字符串)会触发相同错误
3.调试信息: 生产环境中建议隐藏详细错误,可通过环境变量控制:
import os @app.exception_handler(requestvalidationerror) async def handler(...): if os.getenv("env") == "prod": return jsonresponse(status_code=422, content={"error": "invalid params"}) else: # 返回完整错误
测试验证
使用无效参数请求示例路由,将得到类似响应:
{ "code": 422, "message": "参数校验失败", "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)中的参数校验错误由内置处理器处理,自定义处理器不影响文档界面行为。
到此这篇关于python fastapi实现统一处理各种异常的文章就介绍到这了,更多相关python fastapi异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论