diff --git a/gcloud/datastore/connection.py b/gcloud/datastore/connection.py index c262a53e9b62..916599590d83 100644 --- a/gcloud/datastore/connection.py +++ b/gcloud/datastore/connection.py @@ -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 diff --git a/gcloud/datastore/test_connection.py b/gcloud/datastore/test_connection.py index 053e2e0c75b3..487c7b7d6e24 100644 --- a/gcloud/datastore/test_connection.py +++ b/gcloud/datastore/test_connection.py @@ -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): diff --git a/gcloud/exceptions.py b/gcloud/exceptions.py index f56148afd33d..78f641118031 100644 --- a/gcloud/exceptions.py +++ b/gcloud/exceptions.py @@ -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]