Skip to content

Customize Pydantic Error Type (AKA subclassing PydanticCustomError)  #1380

@TiansuYu

Description

@TiansuYu

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

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions