pydantic / pydantic-core

Core validation logic for pydantic written in rust
MIT License
1.39k stars 233 forks source link

Customize Pydantic Error Type (AKA subclassing PydanticCustomError) #1380

Open TiansuYu opened 1 month ago

TiansuYu commented 1 month ago

Initial Checks

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:

Affected Components

sydney-runkle commented 1 month ago

@TiansuYu,

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

sydney-runkle commented 1 month ago

Related to https://github.com/pydantic/pydantic/issues/9686, can probably be done at the same time.