error.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. class URLError(OSError):
  14. # URLError is a sub-type of OSError, but it doesn't share any of
  15. # the implementation. need to override __init__ and __str__.
  16. # It sets self.args for compatibility with other OSError
  17. # subclasses, but args doesn't have the typical format with errno in
  18. # slot 0 and strerror in slot 1. This may be better than nothing.
  19. def __init__(self, reason, filename=None):
  20. self.args = reason,
  21. self.reason = reason
  22. if filename is not None:
  23. self.filename = filename
  24. def __str__(self):
  25. return '<urlopen error %s>' % self.reason
  26. class HTTPError(URLError, urllib.response.addinfourl):
  27. """Raised when HTTP error occurs, but also acts like non-error return"""
  28. __super_init = urllib.response.addinfourl.__init__
  29. def __init__(self, url, code, msg, hdrs, fp):
  30. self.code = code
  31. self.msg = msg
  32. self.hdrs = hdrs
  33. self.fp = fp
  34. self.filename = url
  35. # The addinfourl classes depend on fp being a valid file
  36. # object. In some cases, the HTTPError may not have a valid
  37. # file object. If this happens, the simplest workaround is to
  38. # not initialize the base classes.
  39. if fp is not None:
  40. self.__super_init(fp, hdrs, url, code)
  41. def __str__(self):
  42. return 'HTTP Error %s: %s' % (self.code, self.msg)
  43. def __repr__(self):
  44. return '<HTTPError %s: %r>' % (self.code, self.msg)
  45. # since URLError specifies a .reason attribute, HTTPError should also
  46. # provide this attribute. See issue13211 for discussion.
  47. @property
  48. def reason(self):
  49. return self.msg
  50. @property
  51. def headers(self):
  52. return self.hdrs
  53. @headers.setter
  54. def headers(self, headers):
  55. self.hdrs = headers
  56. class ContentTooShortError(URLError):
  57. """Exception raised when downloaded size does not match content-length."""
  58. def __init__(self, message, content):
  59. URLError.__init__(self, message)
  60. self.content = content