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 c115896 commit 950070a
Showing 1 changed file with 20 additions and 15 deletions.
35 changes: 20 additions & 15 deletions consul/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,22 +72,27 @@ 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}")
if index:
return response.headers["X-Consul-Index"], data
if not index in response.headers:
raise ConsulException(f"Missing index header: {response.headers}")
return response.headers.get["X-Consul-Index"], data
return data

return cb

0 comments on commit 950070a

Please sign in to comment.