pydantic-core icon indicating copy to clipboard operation
pydantic-core copied to clipboard

Customize Pydantic Error Type (AKA subclassing PydanticCustomError)

Open TiansuYu opened this issue 1 year ago • 2 comments

Initial Checks

  • [X] I have searched Google & GitHub for similar requests and couldn't find anything
  • [X] 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 avatar Jul 25 '24 09:07 TiansuYu