mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
3f53cb5980
* Update documentation (#162) * More docs about error handling
41 lines
763 B
Python
41 lines
763 B
Python
from pydantic import BaseModel, PydanticValueError, ValidationError, validator
|
|
|
|
|
|
class NotABarError(PydanticValueError):
|
|
code = 'not_a_bar'
|
|
msg_template = 'value is not a "bar", got "{wrong_value}"'
|
|
|
|
def __init__(self, *, wrong_value: int) -> None:
|
|
super().__init__(wrong_value=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())
|
|
"""
|
|
[
|
|
{
|
|
"ctx": {
|
|
"wrong_value": "ber"
|
|
},
|
|
"loc": [
|
|
"foo"
|
|
],
|
|
"msg": "value is not a \"bar\", got \"ber\"",
|
|
"type": "value_error.not_a_bar"
|
|
}
|
|
]
|
|
"""
|