Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added custom exception (inheriting from KeyError) when deserialization fails #207

Open
wants to merge 2 commits into
base: feat/207
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 DataclassJsonSerializationException
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 DataclassJsonSerializationException(
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
8 changes: 8 additions & 0 deletions dataclasses_json/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class DataclassJsonError(Exception):
def __init__(self, *args: object) -> None:
super().__init__(*args)


class DataclassJsonSerializationException(KeyError):
def __init__(self, *args, **kwargs) -> None:
super(DataclassJsonSerializationException, self).__init__(*args, **kwargs)
26 changes: 23 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import os
from setuptools import setup, find_packages
from distutils.command.register import register as register_orig
from distutils.command.upload import upload as upload_orig


with open('README.md', 'r', encoding='utf8') as f:
readme = f.read()


class register(register_orig):

def _get_rc_file(self):
return os.path.join('.', '.pypirc')


class upload(upload_orig):
def _get_rc_file(self):
return os.path.join('.', '.pypirc')


setup(
name='dataclasses-json',
version='0.4.2',
version='0.4.2-twk',
packages=find_packages(exclude=('tests*',)),
package_data={"dataclasses_json": ["py.typed"]},
author='lidatong',
Expand All @@ -16,6 +32,11 @@
url='https://github.com/lidatong/dataclasses-json',
license='MIT',
keywords='dataclasses json',
cmdclass={
'register': register,
'upload': upload,
},

install_requires=[
'dataclasses;python_version=="3.6"',
'marshmallow>=3.3.0,<4.0.0',
Expand All @@ -35,8 +56,7 @@
'simplejson'
]
},
include_package_data=True,
scripts=['publish.py']
include_package_data=True
)


Expand Down
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 DataclassJsonSerializationException
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(DataclassJsonSerializationException):
actual = DataClassWithDataClass.from_json('{"dc_with_list": {}}')
expected = DataClassWithDataClass(DataClassWithList(None))
assert (actual == expected)
Expand Down