Skip to content

Commit 96d0f9e

Browse files
committed
Merge pull request #1508 from dhermes/fix-1506
Handle expected JSON errors that can't be parsed.
2 parents 38f0afc + 26bec50 commit 96d0f9e

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

gcloud/exceptions.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,9 +181,14 @@ def make_exception(response, content, error_info=None, use_json=True):
181181
content = content.decode('utf-8')
182182

183183
if isinstance(content, six.string_types):
184+
payload = None
184185
if use_json:
185-
payload = json.loads(content)
186-
else:
186+
try:
187+
payload = json.loads(content)
188+
except ValueError:
189+
# Expected JSON but received something else.
190+
pass
191+
if payload is None:
187192
payload = {'error': {'message': content}}
188193
else:
189194
payload = content

gcloud/test_exceptions.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,10 @@ def test_ctor_explicit(self):
4848

4949
class Test_make_exception(unittest2.TestCase):
5050

51-
def _callFUT(self, response, content):
51+
def _callFUT(self, response, content, error_info=None, use_json=True):
5252
from gcloud.exceptions import make_exception
53-
return make_exception(response, content)
53+
return make_exception(response, content, error_info=error_info,
54+
use_json=use_json)
5455

5556
def test_hit_w_content_as_str(self):
5657
from gcloud.exceptions import NotFound
@@ -77,6 +78,15 @@ def test_miss_w_content_as_dict(self):
7778
self.assertEqual(exception.message, 'Unknown Error')
7879
self.assertEqual(list(exception.errors), [ERROR])
7980

81+
def test_html_when_json_expected(self):
82+
from gcloud.exceptions import NotFound
83+
response = _Response(NotFound.code)
84+
content = '<html><body>404 Not Found</body></html>'
85+
exception = self._callFUT(response, content, use_json=True)
86+
self.assertTrue(isinstance(exception, NotFound))
87+
self.assertEqual(exception.message, content)
88+
self.assertEqual(list(exception.errors), [])
89+
8090

8191
class _Response(object):
8292
def __init__(self, status):

0 commit comments

Comments
 (0)