Fix error reporting with unserializable json (#73908)

This commit is contained in:
J. Nick Koston 2022-06-23 13:32:45 -05:00 committed by GitHub
parent b3b4707579
commit fd9fdc6283
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 2 deletions

View file

@ -57,13 +57,15 @@ def save_json(
Returns True on success.
"""
dump: Callable[[Any], Any] = json.dumps
try:
if encoder:
json_data = json.dumps(data, indent=2, cls=encoder)
else:
dump = orjson.dumps
json_data = orjson.dumps(data, option=orjson.OPT_INDENT_2).decode("utf-8")
except TypeError as error:
msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}"
msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data, dump=dump))}"
_LOGGER.error(msg)
raise SerializationError(msg) from error

View file

@ -11,6 +11,7 @@ import pytest
from homeassistant.core import Event, State
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.template import TupleWrapper
from homeassistant.util.json import (
SerializationError,
find_paths_unserializable_data,
@ -72,7 +73,7 @@ def test_overwrite_and_reload(atomic_writes):
def test_save_bad_data():
"""Test error from trying to save unserialisable data."""
"""Test error from trying to save unserializable data."""
with pytest.raises(SerializationError) as excinfo:
save_json("test4", {"hello": set()})
@ -82,6 +83,17 @@ def test_save_bad_data():
)
def test_save_bad_data_tuple_wrapper():
"""Test error from trying to save unserializable data."""
with pytest.raises(SerializationError) as excinfo:
save_json("test4", {"hello": TupleWrapper(("4", "5"))})
assert (
"Failed to serialize to JSON: test4. Bad data at $.hello=('4', '5')(<class 'homeassistant.helpers.template.TupleWrapper'>"
in str(excinfo.value)
)
def test_load_bad_data():
"""Test error from trying to load unserialisable data."""
fname = _path_for("test5")