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

Improve JSON encoding error message #1827

Merged
merged 1 commit into from
Oct 21, 2021
Merged
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
3 changes: 3 additions & 0 deletions python/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
``TableCollection.sort`` no longer sorts individuals.
(:user:`benjeffery`, :issue:`1774`, :pr:`1789`)

- Metadata encoding errors now raise ``MetadataEncodingError``
(:user:`benjeffery`, :issue:`1505`, :pr:`1827`).

**Features**

- Add ``TableCollection.sort_individuals`` to sort the individuals as this is no longer done by the
Expand Down
8 changes: 8 additions & 0 deletions python/tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,14 @@ def test_nested_default_error(self):
):
tskit.MetadataSchema(schema)

def test_bad_type_error(self):
ms = tskit.MetadataSchema({"codec": "json"})
with pytest.raises(
exceptions.MetadataEncodingError,
match="Could not encode metadata of type TableCollection",
):
ms.validate_and_encode_row(tskit.TableCollection(1))


class TestStructCodec:
def encode_decode(self, method_name, sub_schema, obj, buffer):
Expand Down
6 changes: 6 additions & 0 deletions python/tskit/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,9 @@ class MetadataSchemaValidationError(TskitException):
"""
A metadata schema object did not validate against the metaschema.
"""


class MetadataEncodingError(TskitException):
"""
A metadata object was of a type that could not be encoded
"""
7 changes: 6 additions & 1 deletion python/tskit/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,12 @@ def __init__(self, schema: Mapping[str, Any]) -> None:
}

def encode(self, obj: Any) -> bytes:
return tskit.canonical_json(obj).encode()
try:
return tskit.canonical_json(obj).encode()
except TypeError as e:
raise exceptions.MetadataEncodingError(
f"Could not encode metadata of type {str(e).split()[3]}"
)

def decode(self, encoded: bytes) -> Any:
result = json.loads(encoded.decode())
Expand Down