From a5119fa66553a2ffeca50ae19d9f359fd86b93f9 Mon Sep 17 00:00:00 2001 From: Cedric Paillet Date: Thu, 9 Jan 2025 10:39:25 +0100 Subject: [PATCH] Improve robustness of JSON decoding If JSON decoding fails, if a field is missing, or if there are no fields, a ConsulException is returned. --- consul/callback.py | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/consul/callback.py b/consul/callback.py index d4637a2..e127500 100644 --- a/consul/callback.py +++ b/consul/callback.py @@ -72,21 +72,26 @@ def cb(response): if response.code == 404: data = None else: - data = json.loads(response.body) - if decode: - for item in data: - if item.get(decode) is not None: - item[decode] = base64.b64decode(item[decode]) - if is_id: - data = data["ID"] - if one: - if data == []: - data = None - if data is not None: - data = data[0] - if postprocess: - data = postprocess(data) + try: + data = json.loads(response.body) + if decode: + for item in data: + if item.get(decode) is not None: + item[decode] = base64.b64decode(item[decode]) + if is_id: + data = data["ID"] + if one: + if data == []: + data = None + if data is not None: + data = data[0] + if postprocess: + data = postprocess(data) + except (json.JSONDecodeError, TypeError, KeyError) as e: + raise ConsulException(f"Failed to decode JSON: {response.body} {e}") from e if index: + if "X-Consul-Index" not in response.headers: + raise ConsulException(f"Missing index header: {response.headers}") return response.headers["X-Consul-Index"], data return data