1 """Exception classes raised by urllib.
2
3 The base exception class is URLError, which inherits from OSError. It
4 doesn't define any behavior of its own, but is the base class for all
5 exceptions defined in this package.
6
7 HTTPError is an exception class that is also a valid HTTP response
8 instance. It behaves this way because HTTP protocol errors are valid
9 responses, with a status code, headers, and a body. In some contexts,
10 an application may want to handle an exception like a regular
11 response.
12 """
13 import io
14 import urllib.response
15
16 __all__ = ['URLError', 'HTTPError', 'ContentTooShortError']
17
18
19 class ESC[4;38;5;81mURLError(ESC[4;38;5;149mOSError):
20 # URLError is a sub-type of OSError, but it doesn't share any of
21 # the implementation. need to override __init__ and __str__.
22 # It sets self.args for compatibility with other OSError
23 # subclasses, but args doesn't have the typical format with errno in
24 # slot 0 and strerror in slot 1. This may be better than nothing.
25 def __init__(self, reason, filename=None):
26 self.args = reason,
27 self.reason = reason
28 if filename is not None:
29 self.filename = filename
30
31 def __str__(self):
32 return '<urlopen error %s>' % self.reason
33
34
35 class ESC[4;38;5;81mHTTPError(ESC[4;38;5;149mURLError, ESC[4;38;5;149murllibESC[4;38;5;149m.ESC[4;38;5;149mresponseESC[4;38;5;149m.ESC[4;38;5;149maddinfourl):
36 """Raised when HTTP error occurs, but also acts like non-error return"""
37 __super_init = urllib.response.addinfourl.__init__
38
39 def __init__(self, url, code, msg, hdrs, fp):
40 self.code = code
41 self.msg = msg
42 self.hdrs = hdrs
43 self.fp = fp
44 self.filename = url
45 if fp is None:
46 fp = io.BytesIO()
47 self.__super_init(fp, hdrs, url, code)
48
49 def __str__(self):
50 return 'HTTP Error %s: %s' % (self.code, self.msg)
51
52 def __repr__(self):
53 return '<HTTPError %s: %r>' % (self.code, self.msg)
54
55 # since URLError specifies a .reason attribute, HTTPError should also
56 # provide this attribute. See issue13211 for discussion.
57 @property
58 def reason(self):
59 return self.msg
60
61 @property
62 def headers(self):
63 return self.hdrs
64
65 @headers.setter
66 def headers(self, headers):
67 self.hdrs = headers
68
69
70 class ESC[4;38;5;81mContentTooShortError(ESC[4;38;5;149mURLError):
71 """Exception raised when downloaded size does not match content-length."""
72 def __init__(self, message, content):
73 URLError.__init__(self, message)
74 self.content = content