You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI结合Pydantic:如何自定义422 Unprocessable Entity错误信息?

自定义FastAPI 422错误响应格式

当传入参数不符合校验规则时,FastAPI默认返回的422错误格式包含较多细节,若想将其改为更简洁的结构(如{"status": "failed", "error": "value_error.missing"}),可以通过自定义异常处理器实现,步骤如下:

1. 导入依赖模块

需要导入FastAPI核心组件以及异常相关的类:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

2. 定义自定义异常处理器

编写一个函数来捕获RequestValidationError(即触发422错误的异常类型),并构造自定义响应:

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    # 提取第一个错误的类型(若需处理多个错误可遍历exc.errors())
    error_type = exc.errors()[0]["type"]
    # 构造简洁的响应体
    return JSONResponse(
        status_code=422,
        content={"status": "failed", "error": error_type}
    )

3. 注册处理器到FastAPI应用

将自定义处理器绑定到应用实例上:

app = FastAPI()
# 注册自定义异常处理器
app.add_exception_handler(RequestValidationError, validation_exception_handler)

4. 测试示例

添加一个带参数校验的接口进行测试:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return {"name": item.name, "price": item.price}

当不传name或price参数时,接口会返回:

{"status": "failed", "error": "value_error.missing"}

扩展说明

  • 若需要返回所有错误类型,可将error字段改为列表:"error": [err["type"] for err in exc.errors()]
  • 也可以根据需求自定义返回内容,比如提取错误提示信息exc.errors()[0]["msg"]替换error_type

内容的提问来源于stack exchange,提问作者Val

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 09:01:08