error.py 2.4 KB

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