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

Add encoder and decoder exception handling #248

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
28 changes: 24 additions & 4 deletions dataclasses_json/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,14 @@ def _encode_overrides(kvs, overrides, encode_json=False):
)

encoder = overrides[original_key].encoder
v = encoder(v) if encoder is not None else v
# v = encoder(v) if encoder is not None else v
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove commented code

if encoder is not None:
try:
v = encoder(v)
except Exception:
raise ValueError(
f"Encoder encountered an error with field '{k}'"
)

if encode_json:
v = _encode_json_type(v)
Expand Down Expand Up @@ -168,7 +175,13 @@ 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:
raise KeyError(
f"Required field '{field.name}' not found while "
f"decoding into dataclass '{cls.__name__}'"
)
field_type = types[field.name]
if field_value is None:
if not _is_optional(field_type):
Expand Down Expand Up @@ -202,8 +215,15 @@ def _decode_dataclass(cls, kvs, infer_missing):
if field_type is type(field_value):
init_kwargs[field.name] = field_value
else:
init_kwargs[field.name] = overrides[field.name].decoder(
field_value)
try:
init_kwargs[field.name] = overrides[field.name].decoder(
field_value
)
except Exception:
raise ValueError(
f"Decoder encountered an error with field "
f"'{field.name}' in '{cls.__name__}'"
)
elif is_dataclass(field_type):
# FIXME this is a band-aid to deal with the value already being
# serialized when handling nested marshmallow schema
Expand Down
Loading