Skip to content

Improve type validation error messages #5

Closed

Description

@jcrist

Currently the messages that msgspec raises on validation error can be a bit cryptic:

In [1]: import msgspec

In [2]: class User(msgspec.Struct):
   ...:     name: str
   ...:     email: str
   ...:

In [3]: dec = msgspec.Decoder(User)

In [4]: enc = msgspec.Encoder()

In [5]: msg = enc.encode({"name": 1})

In [6]: dec.decode(msg)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-e19f0160a9aa> in <module>
----> 1 dec.decode(msg)

TypeError: Error decoding: expected `str`, got `int`

The message isn't incorrect, but it doesn't provide some necessary context for determining what part of the message was mistyped. For highly nested messages I'm not sure what this would look like. Right now I'm leaning towards something like:

"Error while decoding {context}: {details}"

The idea is to use either the most recent struct field in the type tree before the error, or the top-level compound type as context, then let the error to the right of the : speak for itself.

>>> Decoder(User).decode(...)  # For structs, include struct name, current field, and type of that field
DecodeError("Error while decoding `User.name` (`str`): expected `str`, got `int`")

>>> Decoder(List[User]).decode(...)  # For collections, include collection type
DecodeError("Error while decoding `List[User]`: expected `User`, got `int`")

>>> Decoder(Dict[Tuple[str, str]], User]).decode(...)  # For dicts, specify if in `key` or `value`
DecodeError("Error while decoding `key` of `Dict[Tuple[str, str], str]`: expected `tuple` got `str`")

>>> Decoder(List[User]).decode(...)  # if error is inside a struct, even if top-level is a collection, use struct as context
DecodeError("Error while decoding `User.name` (`str`): expected `str`, got `int`")

The hope is that this will be easy enough to implement in a performant way, while still providing decent error messages for debugging.

Activity

  1. jcrist commented on Feb 22, 2021

    @jcrist
    MemberAuthor

    This has now been resolved since 998c657.

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