Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

exceptions.py 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. from __future__ import annotations
  2. import socket
  3. import typing
  4. import warnings
  5. from email.errors import MessageDefect
  6. from http.client import IncompleteRead as httplib_IncompleteRead
  7. if typing.TYPE_CHECKING:
  8. from .connection import HTTPConnection
  9. from .connectionpool import ConnectionPool
  10. from .response import HTTPResponse
  11. from .util.retry import Retry
  12. # Base Exceptions
  13. class HTTPError(Exception):
  14. """Base exception used by this module."""
  15. class HTTPWarning(Warning):
  16. """Base warning used by this module."""
  17. _TYPE_REDUCE_RESULT = typing.Tuple[
  18. typing.Callable[..., object], typing.Tuple[object, ...]
  19. ]
  20. class PoolError(HTTPError):
  21. """Base exception for errors caused within a pool."""
  22. def __init__(self, pool: ConnectionPool, message: str) -> None:
  23. self.pool = pool
  24. super().__init__(f"{pool}: {message}")
  25. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  26. # For pickling purposes.
  27. return self.__class__, (None, None)
  28. class RequestError(PoolError):
  29. """Base exception for PoolErrors that have associated URLs."""
  30. def __init__(self, pool: ConnectionPool, url: str, message: str) -> None:
  31. self.url = url
  32. super().__init__(pool, message)
  33. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  34. # For pickling purposes.
  35. return self.__class__, (None, self.url, None)
  36. class SSLError(HTTPError):
  37. """Raised when SSL certificate fails in an HTTPS connection."""
  38. class ProxyError(HTTPError):
  39. """Raised when the connection to a proxy fails."""
  40. # The original error is also available as __cause__.
  41. original_error: Exception
  42. def __init__(self, message: str, error: Exception) -> None:
  43. super().__init__(message, error)
  44. self.original_error = error
  45. class DecodeError(HTTPError):
  46. """Raised when automatic decoding based on Content-Type fails."""
  47. class ProtocolError(HTTPError):
  48. """Raised when something unexpected happens mid-request/response."""
  49. #: Renamed to ProtocolError but aliased for backwards compatibility.
  50. ConnectionError = ProtocolError
  51. # Leaf Exceptions
  52. class MaxRetryError(RequestError):
  53. """Raised when the maximum number of retries is exceeded.
  54. :param pool: The connection pool
  55. :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
  56. :param str url: The requested Url
  57. :param reason: The underlying error
  58. :type reason: :class:`Exception`
  59. """
  60. def __init__(
  61. self, pool: ConnectionPool, url: str, reason: Exception | None = None
  62. ) -> None:
  63. self.reason = reason
  64. message = f"Max retries exceeded with url: {url} (Caused by {reason!r})"
  65. super().__init__(pool, url, message)
  66. class HostChangedError(RequestError):
  67. """Raised when an existing pool gets a request for a foreign host."""
  68. def __init__(
  69. self, pool: ConnectionPool, url: str, retries: Retry | int = 3
  70. ) -> None:
  71. message = f"Tried to open a foreign host with url: {url}"
  72. super().__init__(pool, url, message)
  73. self.retries = retries
  74. class TimeoutStateError(HTTPError):
  75. """Raised when passing an invalid state to a timeout"""
  76. class TimeoutError(HTTPError):
  77. """Raised when a socket timeout error occurs.
  78. Catching this error will catch both :exc:`ReadTimeoutErrors
  79. <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
  80. """
  81. class ReadTimeoutError(TimeoutError, RequestError):
  82. """Raised when a socket timeout occurs while receiving data from a server"""
  83. # This timeout error does not have a URL attached and needs to inherit from the
  84. # base HTTPError
  85. class ConnectTimeoutError(TimeoutError):
  86. """Raised when a socket timeout occurs while connecting to a server"""
  87. class NewConnectionError(ConnectTimeoutError, HTTPError):
  88. """Raised when we fail to establish a new connection. Usually ECONNREFUSED."""
  89. def __init__(self, conn: HTTPConnection, message: str) -> None:
  90. self.conn = conn
  91. super().__init__(f"{conn}: {message}")
  92. @property
  93. def pool(self) -> HTTPConnection:
  94. warnings.warn(
  95. "The 'pool' property is deprecated and will be removed "
  96. "in urllib3 v2.1.0. Use 'conn' instead.",
  97. DeprecationWarning,
  98. stacklevel=2,
  99. )
  100. return self.conn
  101. class NameResolutionError(NewConnectionError):
  102. """Raised when host name resolution fails."""
  103. def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror):
  104. message = f"Failed to resolve '{host}' ({reason})"
  105. super().__init__(conn, message)
  106. class EmptyPoolError(PoolError):
  107. """Raised when a pool runs out of connections and no more are allowed."""
  108. class FullPoolError(PoolError):
  109. """Raised when we try to add a connection to a full pool in blocking mode."""
  110. class ClosedPoolError(PoolError):
  111. """Raised when a request enters a pool after the pool has been closed."""
  112. class LocationValueError(ValueError, HTTPError):
  113. """Raised when there is something wrong with a given URL input."""
  114. class LocationParseError(LocationValueError):
  115. """Raised when get_host or similar fails to parse the URL input."""
  116. def __init__(self, location: str) -> None:
  117. message = f"Failed to parse: {location}"
  118. super().__init__(message)
  119. self.location = location
  120. class URLSchemeUnknown(LocationValueError):
  121. """Raised when a URL input has an unsupported scheme."""
  122. def __init__(self, scheme: str):
  123. message = f"Not supported URL scheme {scheme}"
  124. super().__init__(message)
  125. self.scheme = scheme
  126. class ResponseError(HTTPError):
  127. """Used as a container for an error reason supplied in a MaxRetryError."""
  128. GENERIC_ERROR = "too many error responses"
  129. SPECIFIC_ERROR = "too many {status_code} error responses"
  130. class SecurityWarning(HTTPWarning):
  131. """Warned when performing security reducing actions"""
  132. class InsecureRequestWarning(SecurityWarning):
  133. """Warned when making an unverified HTTPS request."""
  134. class NotOpenSSLWarning(SecurityWarning):
  135. """Warned when using unsupported SSL library"""
  136. class SystemTimeWarning(SecurityWarning):
  137. """Warned when system time is suspected to be wrong"""
  138. class InsecurePlatformWarning(SecurityWarning):
  139. """Warned when certain TLS/SSL configuration is not available on a platform."""
  140. class DependencyWarning(HTTPWarning):
  141. """
  142. Warned when an attempt is made to import a module with missing optional
  143. dependencies.
  144. """
  145. class ResponseNotChunked(ProtocolError, ValueError):
  146. """Response needs to be chunked in order to read it as chunks."""
  147. class BodyNotHttplibCompatible(HTTPError):
  148. """
  149. Body should be :class:`http.client.HTTPResponse` like
  150. (have an fp attribute which returns raw chunks) for read_chunked().
  151. """
  152. class IncompleteRead(HTTPError, httplib_IncompleteRead):
  153. """
  154. Response length doesn't match expected Content-Length
  155. Subclass of :class:`http.client.IncompleteRead` to allow int value
  156. for ``partial`` to avoid creating large objects on streamed reads.
  157. """
  158. def __init__(self, partial: int, expected: int) -> None:
  159. self.partial = partial # type: ignore[assignment]
  160. self.expected = expected
  161. def __repr__(self) -> str:
  162. return "IncompleteRead(%i bytes read, %i more expected)" % (
  163. self.partial, # type: ignore[str-format]
  164. self.expected,
  165. )
  166. class InvalidChunkLength(HTTPError, httplib_IncompleteRead):
  167. """Invalid chunk length in a chunked response."""
  168. def __init__(self, response: HTTPResponse, length: bytes) -> None:
  169. self.partial: int = response.tell() # type: ignore[assignment]
  170. self.expected: int | None = response.length_remaining
  171. self.response = response
  172. self.length = length
  173. def __repr__(self) -> str:
  174. return "InvalidChunkLength(got length %r, %i bytes read)" % (
  175. self.length,
  176. self.partial,
  177. )
  178. class InvalidHeader(HTTPError):
  179. """The header provided was somehow invalid."""
  180. class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):
  181. """ProxyManager does not support the supplied scheme"""
  182. # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
  183. def __init__(self, scheme: str | None) -> None:
  184. # 'localhost' is here because our URL parser parses
  185. # localhost:8080 -> scheme=localhost, remove if we fix this.
  186. if scheme == "localhost":
  187. scheme = None
  188. if scheme is None:
  189. message = "Proxy URL had no scheme, should start with http:// or https://"
  190. else:
  191. message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://"
  192. super().__init__(message)
  193. class ProxySchemeUnsupported(ValueError):
  194. """Fetching HTTPS resources through HTTPS proxies is unsupported"""
  195. class HeaderParsingError(HTTPError):
  196. """Raised by assert_header_parsing, but we convert it to a log.warning statement."""
  197. def __init__(
  198. self, defects: list[MessageDefect], unparsed_data: bytes | str | None
  199. ) -> None:
  200. message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}"
  201. super().__init__(message)
  202. class UnrewindableBodyError(HTTPError):
  203. """urllib3 encountered an error when trying to rewind a body"""