Skip to content

Commit

Permalink
Making json.loads() optional in gcloud.exceptions.make_exception.
Browse files Browse the repository at this point in the history
Fixes #626.
  • Loading branch information
dhermes committed Feb 13, 2015
1 parent f73ad7e commit c3e1351
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
2 changes: 1 addition & 1 deletion gcloud/datastore/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _request(self, dataset_id, method, data):

status = headers['status']
if status != '200':
raise make_exception(headers, content)
raise make_exception(headers, content, use_json=False)

return content

Expand Down
4 changes: 2 additions & 2 deletions gcloud/datastore/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ def test__request_not_200(self):
METHOD = 'METHOD'
DATA = 'DATA'
conn = self._makeOne()
conn._http = Http({'status': '400'}, '{"message": "Bad Request"}')
conn._http = Http({'status': '400'}, 'Entity value is indexed.')
with self.assertRaises(BadRequest) as e:
conn._request(DATASET_ID, METHOD, DATA)
expected_message = ('400 Bad Request')
expected_message = '400 Entity value is indexed.'
self.assertEqual(str(e.exception), expected_message)

def test__rpc(self):
Expand Down
27 changes: 22 additions & 5 deletions gcloud/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,18 +155,35 @@ class ServiceUnavailable(ServerError):
code = 503


def make_exception(response, content):
def make_exception(response, content, use_json=True):
"""Factory: create exception based on HTTP response code.
:type response: :class:`httplib2.Response` or other HTTP response object
:param response: A response object that defines a status code as the
status attribute.
:type content: string or dictionary
:param content: The body of the HTTP error response.
:type use_json: boolean
:param use_json: Flag indicating if ``content`` is expected to be JSON.
:rtype: instance of :class:`GCloudError`, or a concrete subclass.
:returns: Exception specific to the error response.
"""
message = content
errors = ()

if isinstance(content, str):
content = json.loads(content)
if use_json:
payload = json.loads(content)
else:
payload = {}
else:
payload = content

message = content.get('message')
error = content.get('error', {})
errors = error.get('errors', ())
message = payload.get('message', message)
errors = payload.get('error', {}).get('errors', ())

try:
klass = _HTTP_CODE_TO_EXCEPTION[response.status]
Expand Down

0 comments on commit c3e1351

Please sign in to comment.