Skip to content

Commit

Permalink
Improve JSON encoding error message
Browse files Browse the repository at this point in the history
  • Loading branch information
benjeffery authored and mergify-bot committed Oct 21, 2021
1 parent 5bd854d commit 647d36f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 1 deletion.
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

0 comments on commit 647d36f

Please sign in to comment.