Skip to content

More details in exceptions #468

Closed
Closed

Description

@vkcku

Description

It would be helpful if we can get the name of the attribute(s) that are invalid within the model when deserializing. This would help in giving improved or custom messages to the end user such as an API response with a list of invalid or missing keys. Currently it is possible to extract this information from the args in the ValidationError object, but that feels a bit hacky and also, I don't think there would be any guarantee the structure of args would stay the same throughout various versions nor would I expect such a guarantee.

For example, consider the below code:

from dataclasses import dataclass
import msgspec

@dataclass
class Foo:

    bar: int

encoded = msgspec.json.encode(Foo("baz"))
try:
    msgspec.json.decode(encoded, type=Foo)
except msgspec.ValidationError as ex:
    print(ex.args) # output: ('Expected `int`, got `str` - at `$.bar`',)    

It would be nice to have something like below:

from dataclasses import dataclass
import msgspec

@dataclass
class Foo:

    bar: int

encoded = msgspec.json.encode(Foo("baz"))
try:
    msgspec.json.decode(encoded, type=Foo)
except msgspec.ValidationError as ex:
    validation_errors = ex.errors()
    # Create custom error message, or raise some custom exception etc.

This is related to #420, but I'm not asking to see the invalid value though. I was hoping for details regarding the error such as which attribute, and why there was a validation error in a more structured manner than being shown now. Something similar to pydantic's ErrorDetails class.

NOTE: This is not a blocker or even a high priority imo. It would just be a nice to have feature if it doesn't create too much difficulty in the implementation or doesn't negatively impact performance too much. That being said, I think one of the weak points of this library is the error messages when a validation error occurs during deserialization.

Activity

  1. jcrist commented on Jul 5, 2023

    @jcrist
    Member

    I believe this is a duplicate of #264 - can you give that issue a read and add any additional feedback there (perhaps copying portions of the above where relevant)? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions