Package googleapiclient :: Module errors |
[hide private]
[frames] | no frames]

# Source Code for Module googleapiclient.errors

      1  # Copyright 2014 Google Inc. All Rights Reserved.
      2  #
      3  # Licensed under the Apache License, Version 2.0 (the "License");
      4  # you may not use this file except in compliance with the License.
      5  # You may obtain a copy of the License at
      6  #
      7  #      http://www.apache.org/licenses/LICENSE-2.0
      8  #
      9  # Unless required by applicable law or agreed to in writing, software
     10  # distributed under the License is distributed on an "AS IS" BASIS,
     11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12  # See the License for the specific language governing permissions and
     13  # limitations under the License.
     14
     15  """Errors for the library.
     16
     17  All exceptions defined by the library
     18  should be defined in this file.
     19  """
     20  from __future__ import absolute_import
     21
     22  __author__ = 'jcgregorio@google.com (Joe Gregorio)'
     23
     24  import json
     25
     26  # Oauth2client < 3 has the positional helper in 'util', >= 3 has it
     27  # in '_helpers'.
     28  try:
     29    from oauth2client import util
     30  except ImportError:
     31    from oauth2client import _helpers as util
     32
     33
     34 -class Error(Exception):
     35    """Base error for this module."""
     36    pass
     37
     38
     39 -class HttpError(Error):
     40    """HTTP data was invalid or unexpected."""
     41
     42    @util.positional(3)
     43 -  def __init__(self, resp, content, uri=None):
     44      self.resp = resp
     45      if not isinstance(content, bytes):
     46          raise TypeError("HTTP content should be bytes")
     47      self.content = content
     48      self.uri = uri
     49
     50 -  def _get_reason(self):
     51      """Calculate the reason for the error from the response content."""
     52      reason = self.resp.reason
     53      try:
     54        data = json.loads(self.content.decode('utf-8'))
     55        if isinstance(data, dict):
     56          reason = data['error']['message']
     57        elif isinstance(data, list) and len(data) > 0:
     58          first_error = data[0]
     59          reason = first_error['error']['message']
     60      except (ValueError, KeyError, TypeError):
     61        pass
     62      if reason is None:
     63        reason = ''
     64      return reason
     65
     66 -  def __repr__(self):
     67      if self.uri:
     68        return '<HttpError %s when requesting %s returned "%s">' % (
     69            self.resp.status, self.uri, self._get_reason().strip())
     70      else:
     71        return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
     72
     73    __str__ = __repr__
     74
     75
     76 -class InvalidJsonError(Error):
     77    """The JSON returned could not be parsed."""
     78    pass
     79
     80
     81 -class UnknownFileType(Error):
     82    """File type unknown or unexpected."""
     83    pass
     84
     85
     86 -class UnknownLinkType(Error):
     87    """Link type unknown or unexpected."""
     88    pass
     89
     90
     91 -class UnknownApiNameOrVersion(Error):
     92    """No API with that name and version exists."""
     93    pass
     94
     95
     96 -class UnacceptableMimeTypeError(Error):
     97    """That is an unacceptable mimetype for this operation."""
     98    pass
     99
    100
    101 -class MediaUploadSizeError(Error):
    102    """Media is larger than the method can accept."""
    103    pass
    104
    105
    106 -class ResumableUploadError(HttpError):
    107    """Error occured during resumable upload."""
    108    pass
    109
    110
    111 -class InvalidChunkSizeError(Error):
    112    """The given chunksize is not valid."""
    113    pass
    114
    115 -class InvalidNotificationError(Error):
    116    """The channel Notification is invalid."""
    117    pass
    118
    119 -class BatchError(HttpError):
    120    """Error occured during batch operations."""
    121
    122    @util.positional(2)
    123 -  def __init__(self, reason, resp=None, content=None):
    124      self.resp = resp
    125      self.content = content
    126      self.reason = reason
    127
    128 -  def __repr__(self):
    129      if getattr(self.resp, 'status', None) is None:
    130        return '<BatchError "%s">' % (self.reason)
    131      else:
    132        return '<BatchError %s "%s">' % (self.resp.status, self.reason)
    133
    134    __str__ = __repr__
    135
    136
    137 -class UnexpectedMethodError(Error):
    138    """Exception raised by RequestMockBuilder on unexpected calls."""
    139
    140    @util.positional(1)
    141 -  def __init__(self, methodId=None):
    142      """Constructor for an UnexpectedMethodError."""
    143      super(UnexpectedMethodError, self).__init__(
    144          'Received unexpected call %s' % methodId)
    145
    146
    147 -class UnexpectedBodyError(Error):
    148    """Exception raised by RequestMockBuilder on unexpected bodies."""
    149
    150 -  def __init__(self, expected, provided):
    151      """Constructor for an UnexpectedMethodError."""
    152      super(UnexpectedBodyError, self).__init__(
    153          'Expected: [%s] - Provided: [%s]' % (expected, provided))
    154