Improve JSON errors from HTTP view (#87042)

This commit is contained in:
Paulus Schoutsen 2023-01-31 14:37:26 -05:00 committed by GitHub
parent 5b728a41de
commit 9c0856787d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 9 deletions

View File

@ -20,7 +20,11 @@ import voluptuous as vol
from homeassistant import exceptions from homeassistant import exceptions
from homeassistant.const import CONTENT_TYPE_JSON from homeassistant.const import CONTENT_TYPE_JSON
from homeassistant.core import Context, is_callback from homeassistant.core import Context, is_callback
from homeassistant.helpers.json import JSON_ENCODE_EXCEPTIONS, json_bytes from homeassistant.helpers.json import JSON_ENCODE_EXCEPTIONS, json_bytes, json_dumps
from homeassistant.util.json import (
find_paths_unserializable_data,
format_unserializable_data,
)
from .const import KEY_AUTHENTICATED, KEY_HASS from .const import KEY_AUTHENTICATED, KEY_HASS
@ -54,7 +58,12 @@ class HomeAssistantView:
try: try:
msg = json_bytes(result) msg = json_bytes(result)
except JSON_ENCODE_EXCEPTIONS as err: except JSON_ENCODE_EXCEPTIONS as err:
_LOGGER.error("Unable to serialize to JSON: %s\n%s", err, result) _LOGGER.error(
"Unable to serialize to JSON. Bad data found at %s",
format_unserializable_data(
find_paths_unserializable_data(result, dump=json_dumps)
),
)
raise HTTPInternalServerError from err raise HTTPInternalServerError from err
response = web.Response( response = web.Response(
body=msg, body=msg,

View File

@ -1,4 +1,5 @@
"""Tests for Home Assistant View.""" """Tests for Home Assistant View."""
from decimal import Decimal
from http import HTTPStatus from http import HTTPStatus
import json import json
from unittest.mock import AsyncMock, Mock from unittest.mock import AsyncMock, Mock
@ -32,18 +33,18 @@ def mock_request_with_stopping():
async def test_invalid_json(caplog): async def test_invalid_json(caplog):
"""Test trying to return invalid JSON.""" """Test trying to return invalid JSON."""
view = HomeAssistantView()
with pytest.raises(HTTPInternalServerError): with pytest.raises(HTTPInternalServerError):
view.json(rb"\ud800") HomeAssistantView.json({"hello": Decimal("2.0")})
assert "Unable to serialize to JSON" in caplog.text assert (
"Unable to serialize to JSON. Bad data found at $.hello=2.0(<class 'decimal.Decimal'>"
in caplog.text
)
async def test_nan_serialized_to_null(caplog): async def test_nan_serialized_to_null():
"""Test nan serialized to null JSON.""" """Test nan serialized to null JSON."""
view = HomeAssistantView() response = HomeAssistantView.json(float("NaN"))
response = view.json(float("NaN"))
assert json.loads(response.body.decode("utf-8")) is None assert json.loads(response.body.decode("utf-8")) is None