From c2db69cffe6166ceb491b82112facc3225adc88b Mon Sep 17 00:00:00 2001 From: Cedric Paillet Date: Thu, 9 Jan 2025 11:27:53 +0100 Subject: [PATCH] code-style: update json CB To avoid too-many-branches in next review. --- consul/callback.py | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/consul/callback.py b/consul/callback.py index d4637a2..f7bb1f8 100644 --- a/consul/callback.py +++ b/consul/callback.py @@ -72,21 +72,23 @@ 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 and isinstance(data, list): + data = data[0] if data else None + 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