Skip to content

Commit b2735a6

Browse files
Gracefully handle non-json error bodies
This updates the JSON error info method to tolerate non-json bodies. These can occur sometimes when the server sends a pre-canned HTML response.
1 parent 082e775 commit b2735a6

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

python-packages/smithy-http/smithy_http/aio/restjson.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,13 @@ async def parse_rest_json_error_info(
3131

3232
if check_body:
3333
if body := await http_response.consume_body_async():
34-
json_body = json.loads(body)
34+
try:
35+
json_body = json.loads(body)
36+
except json.JSONDecodeError:
37+
# In some cases the body might end up being HTML depending on the
38+
# configuration of the server. In those cases we can simply ignore
39+
# the body because we can't find the information we need there.
40+
pass
3541

3642
if json_body:
3743
for key, value in json_body.items():

python-packages/smithy-http/tests/unit/aio/test_restjson.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,21 @@ async def test_parse_rest_json_error_info_without_body(
118118
)
119119
actual = await parse_rest_json_error_info(response, check_body=False)
120120
assert actual == expected
121+
122+
123+
async def test_parse_error_info_non_json_body() -> None:
124+
response = HTTPResponse(
125+
status=400,
126+
fields=tuples_to_fields([]),
127+
body=async_list(
128+
[
129+
(
130+
b"<html>\r\n<head><title>400 Bad Request</title></head>\r\n"
131+
b"<body>\r\n<center><h1>400 Bad Request</h1></center>\r\n</body>\r\n</html>\r\n"
132+
)
133+
]
134+
),
135+
)
136+
expected = RestJsonErrorInfo("Unknown", "Unknown", None)
137+
actual = await parse_rest_json_error_info(response, check_body=True)
138+
assert actual == expected

0 commit comments

Comments
 (0)