pydantic-core
pydantic-core copied to clipboard
Customize Pydantic Error Type (AKA subclassing PydanticCustomError)
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
- [ ] Compatibility between releases
- [X] Data validation/parsing
- [ ] Data serialization -
.model_dump()and.model_dump_json() - [ ] JSON Schema
- [ ] Dataclasses
- [ ] Model Config
- [ ] Field Types - adding or changing a particular data type
- [ ] Function validation decorator
- [ ] Generic Models
- [X] Other Model behaviour -
model_construct(), pickling, private attributes, ORM mode - [ ] Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.