Skip to content

Commit c76fbd6

Browse files
committed
Improve JSON encoding error message
1 parent e5dc0f6 commit c76fbd6

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

python/CHANGELOG.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
``TableCollection.sort`` no longer sorts individuals.
3232
(:user:`benjeffery`, :issue:`1774`, :pr:`1789`)
3333

34+
- Metadata encoding errors now raise ``MetadataEncodingError``
35+
(:user:`benjeffery`, :issue:`1505`, :pr:`1827`).
36+
3437
**Features**
3538

3639
- Add ``TableCollection.sort_individuals`` to sort the individuals as this is no longer done by the

python/tests/test_metadata.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,14 @@ def test_nested_default_error(self):
566566
):
567567
tskit.MetadataSchema(schema)
568568

569+
def test_bad_type_error(self):
570+
ms = tskit.MetadataSchema({"codec": "json"})
571+
with pytest.raises(
572+
exceptions.MetadataEncodingError,
573+
match="Could not encode metadata of type TableCollection",
574+
):
575+
ms.validate_and_encode_row(tskit.TableCollection(1))
576+
569577

570578
class TestStructCodec:
571579
def encode_decode(self, method_name, sub_schema, obj, buffer):

python/tskit/exceptions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,9 @@ class MetadataSchemaValidationError(TskitException):
5454
"""
5555
A metadata schema object did not validate against the metaschema.
5656
"""
57+
58+
59+
class MetadataEncodingError(TskitException):
60+
"""
61+
A metadata object was of a type that could not be encoded
62+
"""

python/tskit/metadata.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,12 @@ def __init__(self, schema: Mapping[str, Any]) -> None:
144144
}
145145

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

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

0 commit comments

Comments
 (0)