mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
f0f9de5f96
* improve docs on error handling * change ValidationError signature * cleanup * rename _raw_errors > raw_errors * improve _display_error_type_and_ctx
32 lines
639 B
Python
32 lines
639 B
Python
from pydantic import BaseModel, PydanticValueError, ValidationError, validator
|
|
|
|
class NotABarError(PydanticValueError):
|
|
code = 'not_a_bar'
|
|
msg_template = 'value is not "bar", got "{wrong_value}"'
|
|
|
|
class Model(BaseModel):
|
|
foo: str
|
|
|
|
@validator('foo')
|
|
def name_must_contain_space(cls, v):
|
|
if v != 'bar':
|
|
raise NotABarError(wrong_value=v)
|
|
return v
|
|
|
|
try:
|
|
Model(foo='ber')
|
|
except ValidationError as e:
|
|
print(e.json())
|
|
"""
|
|
[
|
|
{
|
|
"loc": ["foo"],
|
|
"msg": "value is not \"bar\", got \"ber\"",
|
|
"type": "value_error.not_a_bar",
|
|
"ctx": {
|
|
"wrong_value": "ber"
|
|
}
|
|
}
|
|
]
|
|
"""
|