From 3e24460b245c3d6b0fd75ae65e2178f784146e24 Mon Sep 17 00:00:00 2001 From: Andrew Williams Date: Sun, 14 Nov 2021 16:44:44 +0000 Subject: [PATCH] More error handling for failed queries and unavailable Prometheus --- custom_components/prometheus_query/sensor.py | 25 +++++++++++++------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/custom_components/prometheus_query/sensor.py b/custom_components/prometheus_query/sensor.py index e5a0718..2a0c2ed 100644 --- a/custom_components/prometheus_query/sensor.py +++ b/custom_components/prometheus_query/sensor.py @@ -70,13 +70,22 @@ class PrometheusQuery(SensorEntity): """Fetch new state data for the sensor. This is the only method that should fetch new data for Home Assistant. """ + response_value = STATE_UNKNOWN try: response = requests.get(self._url, params={'query': self._query}) - if (response): - results = response.json()['data']['result'] - self._attr_native_value = results[0]['value'][1] - else: - self._attr_native_value = STATE_UNKNOWN - self._attr_state = self._attr_native_value - except URLCallError: - _LOGGER.error("Error when retrieving update data") + except requests.RequestException: + _LOGGER.exception("Error when querying Prometheus") + else: + if response.ok: + try: + json = response.json() + except requests.exceptions.JSONDecodeError: + _LOGGER.exception("Unable to decode response from Prometheus") + else: + if 'data' in json and 'result' in json['data']: + if len(json['data']['result']): + self._attr_native_value = json['data']['result'][0]['value'][1] + + # Update attributes + self._attr_native_value = response_value + self._attr_state = self._attr_native_value