2

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)
Daniel Bailo
  • 127
  • 1
  • 6
  • Also, please have a look at related answers [here](https://stackoverflow.com/a/72003724/17865804), as well as [here](https://stackoverflow.com/a/72003764/17865804) and [here](https://stackoverflow.com/a/71682274/17865804) – Chris May 17 '23 at 16:58

0 Answers0