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

如何在Pydantic层面移除字段验证错误消息的异常类型前缀

解决方案

方法一:自定义ValidationError异常

直接抛出Pydantic的ValidationError并手动构造错误细节,完全控制错误内容,避免自动添加前缀:

from pydantic import BaseModel, Field, model_validator, ValidationError, ErrorDict

class Product(BaseModel):
    price: float = Field(ge=0, description="Price must be non-negative")

    @model_validator(mode="before")
    def validate_price(cls, values):
        price = values.get("price")
        if price < 0:
            raise ValidationError(
                errors=[
                    ErrorDict(
                        loc=("price",),
                        msg="Price cannot be negative",
                        type="value_error"
                    )
                ],
                model=cls
            )
        return values

try:
    product = Product(price=-100)
except Exception as e:
    print(e)

执行后输出的错误消息不再包含前缀:

1 validation error for Product
  Price cannot be negative [type=value_error, input_value=-100, input_type=int]

方法二:复用内置验证器并自定义错误消息

你已经通过Field(ge=0)设置了非负验证,其实可以直接自定义该内置验证器的错误消息,无需额外编写model_validator,代码更简洁:

from pydantic import BaseModel, Field

class Product(BaseModel):
    price: float = Field(
        ge=0, 
        description="Price must be non-negative",
        error_messages={"ge": "Price cannot be negative"}
    )

try:
    product = Product(price=-100)
except Exception as e:
    print(e)

这种方式下,错误消息会直接显示你定义的内容,没有多余前缀。

如果业务逻辑必须保留自定义model_validator,优先使用方法一。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:12:03