Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 1 | #!/usr/bin/python2.4 |
| 2 | # |
| 3 | # Copyright 2010 Google Inc. All Rights Reserved. |
| 4 | |
| 5 | """Errors for the library. |
| 6 | |
| 7 | All exceptions defined by the library |
| 8 | should be defined in this file. |
| 9 | """ |
| 10 | |
| 11 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 12 | |
| 13 | |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 14 | from anyjson import simplejson |
| 15 | |
| 16 | |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 17 | class Error(Exception): |
| 18 | """Base error for this module.""" |
| 19 | pass |
| 20 | |
| 21 | |
| 22 | class HttpError(Error): |
| 23 | """HTTP data was invalid or unexpected.""" |
| 24 | |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 25 | def __init__(self, resp, content, uri=None): |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 26 | self.resp = resp |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 27 | self.content = content |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 28 | self.uri = uri |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 29 | |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 30 | def _get_reason(self): |
| 31 | """Calculate the reason for the error from the response content. |
| 32 | """ |
| 33 | if self.resp.get('content-type', '').startswith('application/json'): |
| 34 | try: |
| 35 | data = simplejson.loads(self.content) |
| 36 | reason = data['error']['message'] |
| 37 | except (ValueError, KeyError): |
| 38 | reason = self.content |
| 39 | else: |
| 40 | reason = self.resp.reason |
| 41 | return reason |
| 42 | |
| 43 | def __repr__(self): |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 44 | if self.uri: |
| 45 | return '<HttpError %s when requesting %s returned "%s">' % ( |
| 46 | self.resp.status, self.uri, self._get_reason()) |
| 47 | else: |
| 48 | return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 49 | |
| 50 | __str__ = __repr__ |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 51 | |
| 52 | |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 53 | class InvalidJsonError(Error): |
| 54 | """The JSON returned could not be parsed.""" |
| 55 | pass |
| 56 | |
| 57 | |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 58 | class UnknownLinkType(Error): |
| 59 | """Link type unknown or unexpected.""" |
| 60 | pass |