From de91d219bc4a3107ad6cf34e15d0613acf1a8bf0 Mon Sep 17 00:00:00 2001 From: Lewis Marshall Date: Sun, 29 Sep 2024 19:08:46 +0100 Subject: [PATCH] util: Fix decoding msgpack encoding error responses Signed-off-by: Lewis Marshall --- ably/util/exceptions.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/ably/util/exceptions.py b/ably/util/exceptions.py index 8b98c5ee..6ec73bf0 100644 --- a/ably/util/exceptions.py +++ b/ably/util/exceptions.py @@ -1,5 +1,6 @@ import functools import logging +import msgpack log = logging.getLogger(__name__) @@ -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'], @@ -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):