error.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Exception classes raised by urllib.
  2. The base exception class is URLError, which inherits from IOError. It
  3. doesn't define any behavior of its own, but is the base class for all
  4. exceptions defined in this package.
  5. HTTPError is an exception class that is also a valid HTTP response
  6. instance. It behaves this way because HTTP protocol errors are valid
  7. responses, with a status code, headers, and a body. In some contexts,
  8. an application may want to handle an exception like a regular
  9. response.
  10. """
  11. from __future__ import absolute_import, division, unicode_literals
  12. from future import standard_library
  13. from future.backports.urllib import response as urllib_response
  14. __all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
  15. # do these error classes make sense?
  16. # make sure all of the IOError stuff is overridden. we just want to be
  17. # subtypes.
  18. class URLError(IOError):
  19. # URLError is a sub-type of IOError, but it doesn't share any of
  20. # the implementation. need to override __init__ and __str__.
  21. # It sets self.args for compatibility with other EnvironmentError
  22. # subclasses, but args doesn't have the typical format with errno in
  23. # slot 0 and strerror in slot 1. This may be better than nothing.
  24. def __init__(self, reason, filename=None):
  25. self.args = reason,
  26. self.reason = reason
  27. if filename is not None:
  28. self.filename = filename
  29. def __str__(self):
  30. return '<urlopen error %s>' % self.reason
  31. class HTTPError(URLError, urllib_response.addinfourl):
  32. """Raised when HTTP error occurs, but also acts like non-error return"""
  33. __super_init = urllib_response.addinfourl.__init__
  34. def __init__(self, url, code, msg, hdrs, fp):
  35. self.code = code
  36. self.msg = msg
  37. self.hdrs = hdrs
  38. self.fp = fp
  39. self.filename = url
  40. # The addinfourl classes depend on fp being a valid file
  41. # object. In some cases, the HTTPError may not have a valid
  42. # file object. If this happens, the simplest workaround is to
  43. # not initialize the base classes.
  44. if fp is not None:
  45. self.__super_init(fp, hdrs, url, code)
  46. def __str__(self):
  47. return 'HTTP Error %s: %s' % (self.code, self.msg)
  48. # since URLError specifies a .reason attribute, HTTPError should also
  49. # provide this attribute. See issue13211 for discussion.
  50. @property
  51. def reason(self):
  52. return self.msg
  53. def info(self):
  54. return self.hdrs
  55. # exception raised when downloaded size does not match content-length
  56. class ContentTooShortError(URLError):
  57. def __init__(self, message, content):
  58. URLError.__init__(self, message)
  59. self.content = content