Improve logging of mqtt discovery message errors (#94491)

* Improve logging on mqtt discovery message errors

* Create shared helper

* Apply suggestion

* Catch base class vol.Invalid
This commit is contained in:
Jan Bouwhuis 2023-06-12 21:28:28 +02:00 committed by GitHub
parent eb0485ebb0
commit 82b9a31ea7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 7 deletions

View File

@ -244,6 +244,20 @@ class SetupEntity(Protocol):
"""Define setup_entities type."""
@callback
def async_handle_schema_error(
discovery_payload: MQTTDiscoveryPayload, err: vol.MultipleInvalid
) -> None:
"""Help handling schema errors on MQTT discovery messages."""
discovery_topic: str = discovery_payload.discovery_data[ATTR_DISCOVERY_TOPIC]
_LOGGER.error(
"Error '%s' when processing MQTT discovery message topic: '%s', message: '%s'",
err,
discovery_topic,
discovery_payload,
)
async def async_setup_entry_helper(
hass: HomeAssistant,
domain: str,
@ -269,8 +283,15 @@ async def async_setup_entry_helper(
try:
config: DiscoveryInfoType = discovery_schema(discovery_payload)
await async_setup(config, discovery_data=discovery_data)
except vol.Invalid as err:
discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
clear_discovery_hash(hass, discovery_hash)
async_dispatcher_send(
hass, MQTT_DISCOVERY_DONE.format(discovery_hash), None
)
async_handle_schema_error(discovery_payload, err)
except Exception:
discovery_hash: tuple[str, str] = discovery_data[ATTR_DISCOVERY_HASH]
discovery_hash = discovery_data[ATTR_DISCOVERY_HASH]
clear_discovery_hash(hass, discovery_hash)
async_dispatcher_send(
hass, MQTT_DISCOVERY_DONE.format(discovery_hash), None
@ -1037,7 +1058,11 @@ class MqttEntity(
async def discovery_update(self, discovery_payload: MQTTDiscoveryPayload) -> None:
"""Handle updated discovery message."""
config: DiscoveryInfoType = self.config_schema()(discovery_payload)
try:
config: DiscoveryInfoType = self.config_schema()(discovery_payload)
except vol.Invalid as err:
async_handle_schema_error(discovery_payload, err)
return
self._config = config
self._setup_common_attributes_from_config(self._config)
self._setup_from_config(self._config)

View File

@ -1115,7 +1115,6 @@ async def test_discovery_expansion_2(
@patch("homeassistant.components.mqtt.PLATFORMS", [Platform.SWITCH])
@pytest.mark.no_fail_on_log_exception
async def test_discovery_expansion_3(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
@ -1146,10 +1145,7 @@ async def test_discovery_expansion_3(
assert hass.states.get("switch.DiscoveryExpansionTest1") is None
# Make sure the malformed availability data does not trip up discovery by asserting
# there are schema valdiation errors in the log
assert (
"voluptuous.error.MultipleInvalid: expected a dictionary @ data['availability'][0]"
in caplog.text
)
assert "expected a dictionary @ data['availability'][0]" in caplog.text
async def test_discovery_expansion_without_encoding_and_value_template_1(