From 0c9c453be9910c5692d027ff8bf3f46643061d01 Mon Sep 17 00:00:00 2001 From: Mark Schaaf Date: Fri, 11 Jul 2025 12:46:01 -0700 Subject: [PATCH] Fix KeyError exceptions when API returns unexpected response formats (#12) - Add defensive error handling in get_home_chargers() to handle missing 'get_pandas' field - Add validation in get_home_charger_status() to handle missing 'get_panda_status' field - Return empty list for home chargers when response format is unexpected - Raise meaningful exceptions for API errors Fixes #12 --- python_chargepoint/client.py | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/python_chargepoint/client.py b/python_chargepoint/client.py index f065a53..8c47c27 100644 --- a/python_chargepoint/client.py +++ b/python_chargepoint/client.py @@ -261,7 +261,26 @@ def get_home_chargers(self) -> List[int]: ) # {"get_pandas":{"device_ids":[12345678]}} - pandas = response.json()["get_pandas"]["device_ids"] + response_data = response.json() + + # Handle different possible response formats + if "get_pandas" in response_data: + if "device_ids" in response_data["get_pandas"]: + pandas = response_data["get_pandas"]["device_ids"] + else: + # Empty device_ids + pandas = [] + elif "error" in response_data: + raise ChargePointCommunicationException( + response=response, + message=f"API error: {response_data.get('error', 'Unknown error')}" + ) + else: + _LOGGER.error( + "Unexpected API response format. Expected 'get_pandas' field." + ) + # Return empty list instead of failing + pandas = [] _LOGGER.debug( "Discovered %d connected pandas: %s", len(pandas), @@ -292,7 +311,20 @@ def get_home_charger_status(self, charger_id: int) -> HomeChargerStatus: status = response.json() - _LOGGER.debug(status) + if "get_panda_status" not in status: + _LOGGER.error( + "Unexpected API response format. Expected 'get_panda_status' field." + ) + if "error" in status: + raise ChargePointCommunicationException( + response=response, + message=f"API error: {status.get('error', 'Unknown error')}" + ) + # If we don't have the expected response, we can't create a valid status + raise ChargePointCommunicationException( + response=response, + message="Invalid response format for home charger status" + ) return HomeChargerStatus.from_json( charger_id=charger_id, json=status["get_panda_status"]