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 | |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 25 | def __init__(self, resp, content): |
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 | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 28 | |
Ali Afshar | 2dcc652 | 2010-12-16 10:11:53 +0100 | [diff] [blame] | 29 | def _get_reason(self): |
| 30 | """Calculate the reason for the error from the response content. |
| 31 | """ |
| 32 | if self.resp.get('content-type', '').startswith('application/json'): |
| 33 | try: |
| 34 | data = simplejson.loads(self.content) |
| 35 | reason = data['error']['message'] |
| 36 | except (ValueError, KeyError): |
| 37 | reason = self.content |
| 38 | else: |
| 39 | reason = self.resp.reason |
| 40 | return reason |
| 41 | |
| 42 | def __repr__(self): |
| 43 | return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) |
| 44 | |
| 45 | __str__ = __repr__ |
Joe Gregorio | 3ad5e9a | 2010-12-09 15:01:04 -0500 | [diff] [blame] | 46 | |
| 47 | |
| 48 | class UnknownLinkType(Error): |
| 49 | """Link type unknown or unexpected.""" |
| 50 | pass |