dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

Pretty errors when deserializing objects

Open eblis opened this issue 4 years ago • 4 comments

It would be nice if a "pretty" exception was raised when a particular json cannot be mapped to a @dataclass-json object, instead of raising KeyError exceptions.

Right now if the json string cannot be mapped a KeyError exception is raised, saying that a particular field isn't available, but this field might be from a child of a child of the root object and it might be hard to determine which field it's taking about just by the name

eblis avatar Apr 08 '20 18:04 eblis

yep, this would be useful -- i think this is a good opportunity to take a stab at an initial error hierarchy (deserialization, serialization, etc.), as KeyError is just one potential overly-general error, setting the base to a feature branch for now rather than master

lidatong avatar Apr 21 '20 23:04 lidatong

I'm not sure how this library works internally. But I'd just like to add that, not only from_json, but also schema().loads raises a KeyError.

from typing import Optional
from dataclasses import dataclass
from dataclasses_json import DataClassJsonMixin

@dataclass
class MyModel(DataClassJsonMixin):
    required_value: str
    optional_value: Optional[str] = None

MyModel.from_json('{}') # KeyError
MyModel.schema().loads('{}') # KeyError

I would expect that MyModel.schema().loads('{}') raises:

marshmallow.exceptions.ValidationError: {'required_value': ['Missing data for required field.']}

I wanted to mention this because I see you speaking of error hierarchies. My first thought was: "what hierarchy? I just want the marshmallow.exceptions.ValidationError!"

Mtihc avatar May 22 '20 14:05 Mtihc

I would expect that MyModel.schema().loads('{}') raises:

marshmallow.exceptions.ValidationError: {'required_value': ['Missing data for required field.']}

This is really something you'd expect the library to do out of box.

tuukkamustonen avatar Dec 01 '22 11:12 tuukkamustonen

Target of v1 API #442 - take a look.

george-zubrienko avatar Jul 20 '23 22:07 george-zubrienko