Skip to content

Commit

Permalink
Added custom exception (inheriting from KeyError) when deserializatio…
Browse files Browse the repository at this point in the history
…n fails.
  • Loading branch information
eblis committed Apr 15, 2020
1 parent da61c4d commit 7031df5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
10 changes: 9 additions & 1 deletion dataclasses_json/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing_inspect import is_union_type # type: ignore

from dataclasses_json import cfg
from dataclasses_json.errors import DataclassSerializationException
from dataclasses_json.utils import (_get_type_cons,
_handle_undefined_parameters_safe,
_is_collection, _is_mapping, _is_new_type,
Expand Down Expand Up @@ -147,7 +148,14 @@ def _decode_dataclass(cls, kvs, infer_missing):
if not field.init:
continue

field_value = kvs[field.name]
try:
field_value = kvs[field.name]
except KeyError as ex:
qualified = f"{cls.__module__}.{cls.__qualname__}"
args = ", ".join(ex.args)
raise DataclassSerializationException(
f"Error decoding dataclass {qualified} encountered "
f"at field {args}") from ex
field_type = types[field.name]
if field_value is None and not _is_optional(field_type):
warning = (f"value of non-optional type {field.name} detected "
Expand Down
3 changes: 3 additions & 0 deletions dataclasses_json/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class DataclassSerializationException(KeyError):
def __init__(self, *args, **kwargs) -> None:
super(DataclassSerializationException, self).__init__(*args, **kwargs)
3 changes: 2 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import pytest

from dataclasses_json.errors import DataclassSerializationException
from tests.entities import (DataClassBoolImmutableDefault,
DataClassIntImmutableDefault,
DataClassJsonDecorator,
Expand Down Expand Up @@ -127,7 +128,7 @@ def test_warns_when_required_field_is_none(self):

class TestErrors:
def test_error_when_nonoptional_field_is_missing(self):
with pytest.raises(KeyError):
with pytest.raises(DataclassSerializationException):
actual = DataClassWithDataClass.from_json('{"dc_with_list": {}}')
expected = DataClassWithDataClass(DataClassWithList(None))
assert (actual == expected)
Expand Down

0 comments on commit 7031df5

Please sign in to comment.