You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.2 KiB

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