Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion googleapiclient/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def __init__(self, resp, content, uri=None):
raise TypeError("HTTP content should be bytes")
self.content = content
self.uri = uri
self.error_details = ''

def _get_reason(self):
"""Calculate the reason for the error from the response content."""
Expand All @@ -54,17 +55,25 @@ def _get_reason(self):
data = json.loads(self.content.decode('utf-8'))
if isinstance(data, dict):
reason = data['error']['message']
if 'details' in data['error']:
self.error_details = data['error']['details']
elif isinstance(data, list) and len(data) > 0:
first_error = data[0]
reason = first_error['error']['message']
if 'details' in first_error['error']:
self.error_details = first_error['error']['details']
except (ValueError, KeyError, TypeError):
pass
if reason is None:
reason = ''
return reason

def __repr__(self):
if self.uri:
reason = self._get_reason()
if self.error_details:
return '<HttpError %s when requesting %s returned "%s". Details: "%s">' % \
(self.resp.status, self.uri, reason.strip(), self.error_details)
elif self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason().strip())
else:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
}
],
"code": 400,
"message": "country is required"
"message": "country is required",
"details": "error details"
}
}
"""
Expand All @@ -61,7 +62,7 @@ def test_json_body(self):
{'status':'400', 'content-type': 'application/json'},
reason='Failed')
error = HttpError(resp, content, uri='http://example.org')
self.assertEqual(str(error), '<HttpError 400 when requesting http://example.org returned "country is required">')
self.assertEqual(str(error), '<HttpError 400 when requesting http://example.org returned "country is required". Details: "error details">')

def test_bad_json_body(self):
"""Test handling of bodies with invalid json."""
Expand Down