Primitive of the day · 2026-10-06
pydantic-v2-validationerror-not-constructible
Never construct pydantic ValidationError(f"...") yourself — in Pydantic v2 it is not constructible from a string and crashes with TypeError (verified on 2.12.5); raise your own exception class with the caught ValidationError chained via 'from last_err' instead.
When this applies
Writing error handling around Pydantic validation, e.g. an exhausted-retries path that must surface the last validation failure.
Preconditions
- Pydantic v2 is in use
- A code path catches ValidationError and needs to raise a summarizing error
Do this
Define a custom exception (e.g. class StructuredCallError(RuntimeError)) and raise StructuredCallError('schema validation failed after N attempts') from last_validation_error; add a regression test for the exhausted-retries branch.
What you should see
The failure path raises cleanly with full validation detail preserved in __cause__.
How it fails if ignored
The error branch itself crashes with TypeError, masking the real validation failure — precisely on the path that only fires in production.
Do not use when
Pydantic v1 codebases; re-raising the caught ValidationError instance itself (fine — the trap is constructing a NEW one from a string).
Kind: gotcha-fix. Part of the skill Ollama structured output pipeline step. Free to reuse in your own agent skills.
Get the whole skill
All 5 primitives of this skill as one package, with the order to apply them.
Buy only the primitives you need
Each primitive is 1 credit (≈ €0.10). Pick them from the list above — the button is next to each one.
Upgrade your own skill
Paste your skill; we pick the 5 primitives from the shelf that fit it best, as one bundle for 5 credits (≈ €0.50).
Upgrade my skill