Skip to content

Commit e1cac05

Browse files
jjlawrennkgilley
authored andcommitted
Handle bad JSON payloads better
1 parent 753f506 commit e1cac05

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

pyecobee/__init__.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -508,26 +508,32 @@ def _request(
508508
method, url, headers=headers, params=params, json=body
509509
)
510510
_LOGGER.debug(
511-
f"Request response: {response.status_code}: {response.json()}"
511+
f"Request response: {response.status_code}: {response.text}"
512512
)
513513
response.raise_for_status()
514514
return response.json()
515515
except HTTPError:
516+
json_payload = {}
517+
try:
518+
json_payload = response.json()
519+
except json.decoder.JSONDecodeError:
520+
_LOGGER.debug("Invalid JSON payload received")
521+
516522
if auth_request:
517523
if (
518524
response.status_code == 400
519-
and response.json()["error"] == "invalid_grant"
525+
and json_payload.get("error") == "invalid_grant"
520526
):
521527
raise InvalidTokenError(
522528
"ecobee tokens invalid; re-authentication required"
523529
)
524530
else:
525531
_LOGGER.error(
526532
f"Error requesting authorization from ecobee: "
527-
f"{response.status_code}: {response.json()}"
533+
f"{response.status_code}: {json_payload}"
528534
)
529535
elif response.status_code == 500:
530-
code = response.json()["status"]["code"]
536+
code = json_payload.get("status", {}).get("code")
531537
if code in [1, 16]:
532538
raise InvalidTokenError(
533539
"ecobee tokens invalid; re-authentication required"
@@ -539,12 +545,12 @@ def _request(
539545
else:
540546
_LOGGER.error(
541547
f"Error from ecobee while attempting to {log_msg_action}: "
542-
f"{code}: {response.json()['status']['message']}"
548+
f"{code}: {json_payload.get('status', {}).get('message', 'Unknown error')}"
543549
)
544550
else:
545551
_LOGGER.error(
546552
f"Error from ecobee while attempting to {log_msg_action}: "
547-
f"{response.status_code}: {response.json()}"
553+
f"{response.status_code}: {json_payload}"
548554
)
549555
except (RequestException, json.decoder.JSONDecodeError):
550556
_LOGGER.error(

0 commit comments

Comments
 (0)