Skip to content

Commit

Permalink
Merge pull request #571 from ably/fix-error-decoding
Browse files Browse the repository at this point in the history
util: Fix decoding msgpack encoded error responses
  • Loading branch information
lmars authored Oct 1, 2024
2 parents 4066ce3 + de91d21 commit b072909
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions ably/util/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import functools
import logging
import msgpack


log = logging.getLogger(__name__)
Expand Down Expand Up @@ -35,17 +36,17 @@ def raise_for_response(response):
return

try:
json_response = response.json()
decoded_response = AblyException.decode_error_response(response)
except Exception:
log.debug("Response not json: %d %s",
log.debug("Response not json or msgpack: %d %s",
response.status_code,
response.text)
raise AblyException(message=response.text,
status_code=response.status_code,
code=response.status_code * 100)

if json_response and 'error' in json_response:
error = json_response['error']
if decoded_response and 'error' in decoded_response:
error = decoded_response['error']
try:
raise AblyException(
message=error['message'],
Expand All @@ -61,6 +62,17 @@ def raise_for_response(response):
status_code=response.status_code,
code=response.status_code * 100)

@staticmethod
def decode_error_response(response):
content_type = response.headers.get('content-type')
if isinstance(content_type, str):
if content_type.startswith('application/x-msgpack'):
return msgpack.unpackb(response.content)
elif content_type.startswith('application/json'):
return response.json()

raise ValueError("Unsupported content type")

@staticmethod
def from_exception(e):
if isinstance(e, AblyException):
Expand Down

0 comments on commit b072909

Please sign in to comment.