I want to create a new exception that extends ValidationError
and add some attributes and raise this new exception instead of ValidationError
. I have a model that contains various attributes and I don't want to create a raise
for each value, because the ValidationError
already is raised when the value is not filled, for example.
Code example:
from pydantic import BaseModel
class Foo(BaseModel):
number: int
x = Foo()
will throw:
Traceback (most recent call last):
File "/home/daniel/Projects/clients-safra/source/foo.py", line 7, in <module>
x = Foo()
File "/home/daniel/.pyenv/versions/safra-env/lib/python3.10/site-packages/pydantic/main.py", line 406, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for Foo
number
field required (type=value_error.missing)
I want to do this:
from pydantic import BaseModel, ValidationError
class MyValidationError(ValidationError):
error-code:str = 'my-code'
class Foo(BaseModel):
number: int
# DO ANYTHING TO RAISES `MyValidationError`
# I THINK SOMETHING ABOUT `class Config`
x = Foo()
and expected to raises my exception:
Traceback (most recent call last):
File "/home/daniel/Projects/clients-safra/source/foo.py", line 7, in <module>
x = Foo()
File "/home/daniel/.pyenv/versions/safra-env/lib/python3.10/site-packages/pydantic/main.py", line 406, in __init__
raise validation_error
MyValidationError: 1 validation error for Foo
number
field required (type=value_error.missing)