blob: 0d81ec34d1b10eb7be710a487e4042198fef08eb [file] [log] [blame]
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -05001#!/usr/bin/python2.4
2#
3# Copyright 2010 Google Inc. All Rights Reserved.
4
5"""Errors for the library.
6
7All exceptions defined by the library
8should be defined in this file.
9"""
10
11__author__ = 'jcgregorio@google.com (Joe Gregorio)'
12
13
Ali Afshar2dcc6522010-12-16 10:11:53 +010014from anyjson import simplejson
15
16
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -050017class Error(Exception):
18 """Base error for this module."""
19 pass
20
21
22class HttpError(Error):
23 """HTTP data was invalid or unexpected."""
24
Joe Gregorio49396552011-03-08 10:39:00 -050025 def __init__(self, resp, content, uri=None):
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -050026 self.resp = resp
Ali Afshar2dcc6522010-12-16 10:11:53 +010027 self.content = content
Joe Gregorio49396552011-03-08 10:39:00 -050028 self.uri = uri
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -050029
Ali Afshar2dcc6522010-12-16 10:11:53 +010030 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 Gregorio49396552011-03-08 10:39:00 -050044 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 Afshar2dcc6522010-12-16 10:11:53 +010049
50 __str__ = __repr__
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -050051
52
Joe Gregorio49396552011-03-08 10:39:00 -050053class InvalidJsonError(Error):
54 """The JSON returned could not be parsed."""
55 pass
56
57
Joe Gregorio3ad5e9a2010-12-09 15:01:04 -050058class UnknownLinkType(Error):
59 """Link type unknown or unexpected."""
60 pass