From c0c8725da96bdae597f2e5475ce0fb4e745aedec Mon Sep 17 00:00:00 2001 From: G Johansson Date: Wed, 25 Nov 2026 09:21:31 +0100 Subject: [PATCH] Add the target to the error log of a failed action call (#194287) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/api/__init__.py | 17 ++++- .../components/websocket_api/commands.py | 22 +++++- tests/components/api/test_init.py | 39 ++++++++++ .../components/websocket_api/test_commands.py | 74 ++++++++++++++++++- 4 files changed, 147 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/api/__init__.py b/homeassistant/components/api/__init__.py index a66f75403c21..c0a9c37612f6 100644 --- a/homeassistant/components/api/__init__.py +++ b/homeassistant/components/api/__init__.py @@ -36,6 +36,7 @@ from homeassistant.const import ( URL_API_STATES, URL_API_STREAM, URL_API_TEMPLATE, + TargetKey, ) from homeassistant.core import Event, EventStateChangedData, HomeAssistant from homeassistant.exceptions import ( @@ -463,7 +464,21 @@ class APIDomainServicesView(HomeAssistantView): # Handled by the view wrapper, which maps it to 401 raise except HomeAssistantError as ex: - _LOGGER.error("Error during service call to %s.%s: %s", domain, service, ex) + call_data = data if isinstance(data, dict) else {} + if target := { + key: value for key, value in call_data.items() if key in TargetKey + }: + _LOGGER.error( + "Error during service call to %s.%s with target %s: %s", + domain, + service, + target, + ex, + ) + else: + _LOGGER.error( + "Error during service call to %s.%s: %s", domain, service, ex + ) return self.json_message(str(ex), HTTPStatus.INTERNAL_SERVER_ERROR) finally: cancel_listen() diff --git a/homeassistant/components/websocket_api/commands.py b/homeassistant/components/websocket_api/commands.py index 40e4acdf6443..a5e904ab193a 100644 --- a/homeassistant/components/websocket_api/commands.py +++ b/homeassistant/components/websocket_api/commands.py @@ -17,6 +17,7 @@ from homeassistant.const import ( EVENT_STATE_CHANGED, MATCH_ALL, SIGNAL_BOOTSTRAP_INTEGRATIONS, + TargetKey, ) from homeassistant.core import ( Context, @@ -411,9 +412,24 @@ async def handle_call_service( translation_placeholders=err.translation_placeholders, ) except HomeAssistantError as err: - connection.logger.error( - "Error during service call to %s.%s: %s", msg["domain"], msg["service"], err - ) + call_data = {**msg.get("service_data", {}), **msg.get("target", {})} + if target := { + key: value for key, value in call_data.items() if key in TargetKey + }: + connection.logger.error( + "Error during service call to %s.%s with target %s: %s", + msg["domain"], + msg["service"], + target, + err, + ) + else: + connection.logger.error( + "Error during service call to %s.%s: %s", + msg["domain"], + msg["service"], + err, + ) connection.logger.debug("", exc_info=True) connection.send_error( msg["id"], diff --git a/tests/components/api/test_init.py b/tests/components/api/test_init.py index 62a442fa865e..f37eddc72489 100644 --- a/tests/components/api/test_init.py +++ b/tests/components/api/test_init.py @@ -981,6 +981,45 @@ async def test_api_call_service_raises( assert await resp.json() == {"message": str(error)} +@pytest.mark.parametrize( + ("body", "log_message"), + [ + pytest.param( + {"brightness": 10}, + "Error during service call to test_domain.test_service: " + "device did not respond", + id="no_target", + ), + pytest.param( + {"entity_id": "light.kitchen", "brightness": 10}, + "Error during service call to test_domain.test_service with target " + "{'entity_id': 'light.kitchen'}: device did not respond", + id="target", + ), + ], +) +async def test_api_call_service_error_logs_target( + hass: HomeAssistant, + mock_api_client: TestClient, + caplog: pytest.LogCaptureFixture, + body: dict[str, Any], + log_message: str, +) -> None: + """Test the error log of a failed service call names the target.""" + + async def handler(service_call: ha.ServiceCall) -> None: + """Raise an error.""" + raise HomeAssistantError("device did not respond") + + hass.services.async_register("test_domain", "test_service", handler) + + resp = await mock_api_client.post( + "/api/services/test_domain/test_service", json=body + ) + assert resp.status == HTTPStatus.INTERNAL_SERVER_ERROR + assert log_message in caplog.text + + async def test_api_call_service_unauthorized( hass: HomeAssistant, mock_api_client: TestClient ) -> None: diff --git a/tests/components/websocket_api/test_commands.py b/tests/components/websocket_api/test_commands.py index 5685121766e3..fee5a5293adc 100644 --- a/tests/components/websocket_api/test_commands.py +++ b/tests/components/websocket_api/test_commands.py @@ -56,7 +56,14 @@ from homeassistant.const import ( SIGNAL_BOOTSTRAP_INTEGRATIONS, EntityCategory, ) -from homeassistant.core import Context, HomeAssistant, State, SupportsResponse, callback +from homeassistant.core import ( + Context, + HomeAssistant, + ServiceCall, + State, + SupportsResponse, + callback, +) from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import ( area_registry as ar, @@ -880,6 +887,71 @@ async def test_call_service_error( assert "Traceback" in caplog.text +@pytest.mark.parametrize( + ("call_data", "log_message"), + [ + pytest.param( + {}, + "Error during service call to domain_test.ha_error: device did not respond", + id="no_target", + ), + pytest.param( + {"service_data": {"brightness": 10}}, + "Error during service call to domain_test.ha_error: device did not respond", + id="no_target_in_service_data", + ), + pytest.param( + {"target": {"entity_id": "light.kitchen"}}, + "Error during service call to domain_test.ha_error with target " + "{'entity_id': ['light.kitchen']}: device did not respond", + id="target", + ), + pytest.param( + {"service_data": {"entity_id": "light.kitchen", "brightness": 10}}, + "Error during service call to domain_test.ha_error with target " + "{'entity_id': 'light.kitchen'}: device did not respond", + id="target_in_service_data", + ), + pytest.param( + { + "target": {"area_id": "kitchen"}, + "service_data": {"device_id": "abc123"}, + }, + "Error during service call to domain_test.ha_error with target " + "{'device_id': 'abc123', 'area_id': ['kitchen']}: device did not respond", + id="target_and_service_data", + ), + ], +) +async def test_call_service_error_logs_target( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + websocket_client: MockHAClientWebSocket, + call_data: dict[str, Any], + log_message: str, +) -> None: + """Test the error log of a failed service call names the target.""" + + @callback + def ha_error_call(_: ServiceCall) -> None: + raise HomeAssistantError("device did not respond") + + hass.services.async_register("domain_test", "ha_error", ha_error_call) + + await websocket_client.send_json_auto_id( + { + "type": "call_service", + "domain": "domain_test", + "service": "ha_error", + **call_data, + } + ) + + msg = await websocket_client.receive_json() + assert msg["success"] is False + assert log_message in caplog.text + + async def test_subscribe_unsubscribe_events( hass: HomeAssistant, websocket_client ) -> None: