Wrap dec_hook errors in ValidationError - #460
Merged
Merged
Conversation
This modifies decoding of custom types to wrap errors raised by a `dec_hook` with `ValidationError`. Only `TypeError` or `ValueError` (and subclasses) exceptions are wrapped, all other exceptions are raised directly. If an exception is wrapped with a `ValidationError`, the original exception is set as the `__cause__` (and `__context__`). This means the original exception will still show up in tracebacks, and is available for introspection if needed. This also changes the recommendation for raising `TypeError` on unsupported types in `dec_hook`/`enc_hook` to raising a `NotImplementedError`. No previous functionality was based on this recommendation, so this isn't a breaking change in anyway, just a change in recommendation of how best to use `msgspec`.
Member
Author
|
Demo of behavior In [1]: import msgspec, pydantic
In [2]: class Point(pydantic.BaseModel):
...: x: int
...: y: int
...:
In [3]: class Test(msgspec.Struct):
...: point: Point
...:
In [4]: def dec_hook(typ, val):
...: if issubclass(typ, pydantic.BaseModel):
...: return typ.model_validate(val)
...: raise NotImplementedError
...:
In [5]: dec = msgspec.json.Decoder(type=Test, dec_hook=dec_hook)
In [6]: dec.decode(b'{"point": {"x": 1, "y": 2}}') # works
Out[6]: Test(point=Point(x=1, y=2))
In [7]: try:
...: dec.decode(b'{"point": {"x": "a", "y": "b"}}')
...: except msgspec.ValidationError as exc:
...: error = exc # work around auto-del of exc
...:
In [8]: error
Out[8]: msgspec.ValidationError("2 validation errors for Point\nx\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]\n For further information visit https://errors.pydantic.dev/0.39.0/v/int_parsing\ny\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]\n For further information visit https://errors.pydantic.dev/0.39.0/v/int_parsing - at `$.point`")
In [9]: error.__cause__
Out[9]:
2 validation errors for Point
x
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
For further information visit https://errors.pydantic.dev/0.39.0/v/int_parsing
y
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str]
For further information visit https://errors.pydantic.dev/0.39.0/v/int_parsingIf the |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This modifies decoding of custom types to wrap errors raised by a
dec_hookwithValidationError. OnlyTypeErrororValueError(and subclasses) exceptions are wrapped, all other exceptions are raised directly.If an exception is wrapped with a
ValidationError, the original exception is set as the__cause__(and__context__). This means the original exception will still show up in tracebacks, and is available for introspection if needed.This also changes the recommendation for raising
TypeErroron unsupported types indec_hook/enc_hookto raising aNotImplementedError. No previous functionality was based on this recommendation, so this isn't a breaking change in anyway, just a change in recommendation of how best to usemsgspec.Fixes #456.