Suppress exception stack trace when writing MQTT entity state if a ValueError occured (#149583)

This commit is contained in:
Jan Bouwhuis 2025-07-30 09:06:15 +02:00 committed by GitHub
parent 45ae34cc0e
commit 0dd1e0cabb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 6 deletions

View File

@ -364,6 +364,15 @@ class EntityTopicState:
entity_id, entity = self.subscribe_calls.popitem()
try:
entity.async_write_ha_state()
except ValueError as exc:
_LOGGER.error(
"Value error while updating state of %s, topic: "
"'%s' with payload: %s: %s",
entity_id,
msg.topic,
msg.payload,
exc,
)
except Exception:
_LOGGER.exception(
"Exception raised while updating state of %s, topic: "

View File

@ -604,6 +604,23 @@ def test_entity_device_info_schema() -> None:
)
@pytest.mark.parametrize(
("side_effect", "error_message"),
[
(
ValueError("Invalid value for sensor"),
"Value error while updating "
"state of sensor.test_sensor, topic: 'test/state' "
"with payload: b'payload causing errors'",
),
(
TypeError("Invalid value for sensor"),
"Exception raised while updating "
"state of sensor.test_sensor, topic: 'test/state' "
"with payload: b'payload causing errors'",
),
],
)
@pytest.mark.parametrize(
"hass_config",
[
@ -625,6 +642,8 @@ async def test_handle_logging_on_writing_the_entity_state(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
side_effect: Exception,
error_message: str,
) -> None:
"""Test on log handling when an error occurs writing the state."""
await mqtt_mock_entry()
@ -637,7 +656,7 @@ async def test_handle_logging_on_writing_the_entity_state(
assert state.state == "initial_state"
with patch(
"homeassistant.helpers.entity.Entity.async_write_ha_state",
side_effect=ValueError("Invalid value for sensor"),
side_effect=side_effect,
):
async_fire_mqtt_message(hass, "test/state", b"payload causing errors")
await hass.async_block_till_done()
@ -645,11 +664,7 @@ async def test_handle_logging_on_writing_the_entity_state(
assert state is not None
assert state.state == "initial_state"
assert "Invalid value for sensor" in caplog.text
assert (
"Exception raised while updating "
"state of sensor.test_sensor, topic: 'test/state' "
"with payload: b'payload causing errors'" in caplog.text
)
assert error_message in caplog.text
async def test_receiving_non_utf8_message_gets_logged(