Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customize Pydantic Error Type (AKA subclassing PydanticCustomError) #1380

Closed
4 of 13 tasks
TiansuYu opened this issue Jul 25, 2024 · 3 comments
Closed
4 of 13 tasks

Customize Pydantic Error Type (AKA subclassing PydanticCustomError) #1380

TiansuYu opened this issue Jul 25, 2024 · 3 comments
Assignees
Labels
enhancement New feature or request

Comments

@TiansuYu
Copy link

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

I would like to subclass the pydantic_core.PydanticCustomError such that each time a specific field_validator fails, it can raise a MySpecificError instead of the normal pydantic ones.

Currently, PydanticCustomerError is marked as @final and as such, subclassing will lead to TypeError: type 'pydantic_core._pydantic_core.PydanticCustomError' is not an acceptable base type.

Futhermore, I have specific needs to do downstream error handling based on MyTypeAError(PydanticCustomError) and MyTypeBError(PydanticCustomError). Currently, this is not possible.

I know workarounds would be wrap around the model creation step Model(field_a=xxx, field_b=xxx) with a catch block, but still, I do not want to involve my lib user to accept this complicated user experience.

Please let me know:

  • If this is a feature could be added into Pydantic;
  • If there are any workarounds for this (e.g. add some additional logic into BaseModel.__init__).

Affected Components

@TiansuYu TiansuYu changed the title PydanticCustomError should allow subclassing Customize Pydantic Error Type (AKA subclassing PydanticCustomError) Jul 25, 2024
@sydney-runkle
Copy link
Member

@TiansuYu,

This seems reasonable - let's move this to pydantic-core - hopefully we could just remove the @final decorator.

@sydney-runkle sydney-runkle transferred this issue from pydantic/pydantic Jul 30, 2024
@sydney-runkle sydney-runkle added enhancement New feature or request and removed unconfirmed labels Aug 16, 2024
@sydney-runkle
Copy link
Member

Related to pydantic/pydantic#9686, can probably be done at the same time.

@sydney-runkle
Copy link
Member

Closed by #1413

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants