Skip to content

Commit 25cd238

Browse files
authored
improve JSON decode error handling to include response content in client.request_ws() (#111)
* improve JSON decode error handling to include response content in client.request_ws() * fix formatting and linting issues
1 parent 519cfd8 commit 25cd238

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88

9+
### CHANGED
10+
11+
- #[110](https://github.com/braincube-io/python-connector/issues/110): Improved JSON decode error messages in client.request_ws() to include response content when the server returns non-JSON responses.
12+
913
## [2.7.0 - 2025-01-09](https://github.com/braincube-io/python-connector/compare/2.6.1...2.7.0)
1014

1115
### CHANGED

braincube_connector/client.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,15 @@ def request_ws(
100100
)
101101
request_result.raise_for_status()
102102
if response_as_json:
103-
return request_result.json()
103+
try:
104+
return request_result.json()
105+
except requests.exceptions.JSONDecodeError as json_error:
106+
error_msg = "Invalid JSON response: {0}. Response content: {1}".format(
107+
json_error, request_result.text
108+
)
109+
raise requests.exceptions.JSONDecodeError(
110+
error_msg, request_result.text, 0
111+
) from json_error
104112
return request_result
105113

106114
def get_braincube_infos(self) -> Dict[str, Any]:

tests/test_client.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,27 @@ def test_request_ws_succes_no_json(mock_client):
6363
assert type(result) == requests.models.Response
6464

6565

66+
@responses.activate
67+
def test_request_ws_json_decode_error_with_content(mock_client):
68+
"""Test whether request_ws includes response content in JSON decode error messages."""
69+
# Mock a response that returns non-JSON content
70+
responses.add(
71+
responses.GET,
72+
LOAD_URL,
73+
body="<html><body>Response content not JSON</body></html>",
74+
status=200,
75+
)
76+
77+
with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
78+
mock_client.request_ws("path", response_as_json=True)
79+
80+
# Check that the error message contains the response content
81+
error_message = str(excinfo.value)
82+
assert "Invalid JSON response" in error_message
83+
assert "Response content:" in error_message
84+
assert "<html><body>Response content not JSON</body></html>" in error_message
85+
86+
6687
@responses.activate
6788
def test_request_braincubes(mock_client):
6889
"""Test the _request_braincubes method"""

0 commit comments

Comments
 (0)