error.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Exception classes raised by urllib.
  2. The base exception class is URLError, which inherits from OSError. 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. import urllib.response
  12. __all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
  13. # do these error classes make sense?
  14. # make sure all of the OSError stuff is overridden. we just want to be
  15. # subtypes.
  16. class URLError(OSError):
  17. # URLError is a sub-type of OSError, but it doesn't share any of
  18. # the implementation. need to override __init__ and __str__.
  19. # It sets self.args for compatibility with other EnvironmentError
  20. # subclasses, but args doesn't have the typical format with errno in
  21. # slot 0 and strerror in slot 1. This may be better than nothing.
  22. def __init__(self, reason, filename=None):
  23. self.args = reason,
  24. self.reason = reason
  25. if filename is not None:
  26. self.filename = filename
  27. def __str__(self):
  28. return '<urlopen error %s>' % self.reason
  29. class HTTPError(URLError, urllib.response.addinfourl):
  30. """Raised when HTTP error occurs, but also acts like non-error return"""
  31. __super_init = urllib.response.addinfourl.__init__
  32. def __init__(self, url, code, msg, hdrs, fp):
  33. self.code = code
  34. self.msg = msg
  35. self.hdrs = hdrs
  36. self.fp = fp
  37. self.filename = url
  38. # The addinfourl classes depend on fp being a valid file
  39. # object. In some cases, the HTTPError may not have a valid
  40. # file object. If this happens, the simplest workaround is to
  41. # not initialize the base classes.
  42. if fp is not None:
  43. self.__super_init(fp, hdrs, url, code)
  44. def __str__(self):
  45. return 'HTTP Error %s: %s' % (self.code, self.msg)
  46. def __repr__(self):
  47. return '<HTTPError %s: %r>' % (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. @property
  54. def headers(self):
  55. return self.hdrs
  56. @headers.setter
  57. def headers(self, headers):
  58. self.hdrs = headers
  59. class ContentTooShortError(URLError):
  60. """Exception raised when downloaded size does not match content-length."""
  61. def __init__(self, message, content):
  62. URLError.__init__(self, message)
  63. self.content = content