Improve error displaying, and move error display logic into the error module.
diff --git a/apiclient/errors.py b/apiclient/errors.py
index b3a7d13..6a91e1e 100644
--- a/apiclient/errors.py
+++ b/apiclient/errors.py
@@ -11,6 +11,9 @@
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
+from anyjson import simplejson
+
+
class Error(Exception):
"""Base error for this module."""
pass
@@ -19,12 +22,28 @@
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
- def __init__(self, resp, detail):
+ def __init__(self, resp, content):
self.resp = resp
- self.detail = detail
+ self.content = content
- def __str__(self):
- return self.detail
+ def _get_reason(self):
+ """Calculate the reason for the error from the response content.
+ """
+ if self.resp.get('content-type', '').startswith('application/json'):
+ try:
+ data = simplejson.loads(self.content)
+ reason = data['error']['message']
+ except (ValueError, KeyError):
+ reason = self.content
+ else:
+ reason = self.resp.reason
+ return reason
+
+ def __repr__(self):
+ return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
+
+ __str__ = __repr__
+
class UnknownLinkType(Error):
diff --git a/apiclient/model.py b/apiclient/model.py
index f37a699..cd81c0b 100644
--- a/apiclient/model.py
+++ b/apiclient/model.py
@@ -99,7 +99,4 @@
return body
else:
logging.debug('Content from bad request was: %s' % content)
- if resp.get('content-type', '').startswith('application/json'):
- raise HttpError(resp, simplejson.loads(content)['error'])
- else:
- raise HttpError(resp, '%d %s' % (resp.status, resp.reason))
+ raise HttpError(resp, content)