Skip to content

Commit

Permalink
Improve robustness of JSON decoding
Browse files Browse the repository at this point in the history
If JSON decoding fails, if a field is missing, or if there are no fields, a ConsulException is returned.
  • Loading branch information
cpaillet committed Jan 9, 2025
1 parent bdd8253 commit 269e497
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions consul/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +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 and isinstance(data, list):
data = data[0] if data else None
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

Expand Down

0 comments on commit 269e497

Please sign in to comment.