如何在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
相关产品推荐
相关产品推荐

