error.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. # -*- test-case-name: twisted.web.test.test_error -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Exception definitions for L{twisted.web}.
  6. """
  7. __all__ = [
  8. "Error",
  9. "PageRedirect",
  10. "InfiniteRedirection",
  11. "RenderError",
  12. "MissingRenderMethod",
  13. "MissingTemplateLoader",
  14. "UnexposedMethodError",
  15. "UnfilledSlot",
  16. "UnsupportedType",
  17. "FlattenerError",
  18. "RedirectWithNoLocation",
  19. ]
  20. from collections.abc import Sequence
  21. from typing import Optional, Union, cast
  22. from twisted.python.compat import nativeString
  23. from twisted.web._responses import RESPONSES
  24. def _codeToMessage(code: Union[int, bytes]) -> Optional[bytes]:
  25. """
  26. Returns the response message corresponding to an HTTP code, or None
  27. if the code is unknown or unrecognized.
  28. @param code: HTTP status code, for example C{http.NOT_FOUND}.
  29. @return: A string message or none
  30. """
  31. try:
  32. return RESPONSES.get(int(code))
  33. except (ValueError, AttributeError):
  34. return None
  35. class Error(Exception):
  36. """
  37. A basic HTTP error.
  38. @ivar status: Refers to an HTTP status code, for example C{http.NOT_FOUND}.
  39. @param message: A short error message, for example "NOT FOUND".
  40. @ivar response: A complete HTML document for an error page.
  41. """
  42. status: bytes
  43. message: Optional[bytes]
  44. response: Optional[bytes]
  45. def __init__(
  46. self,
  47. code: Union[int, bytes],
  48. message: Optional[bytes] = None,
  49. response: Optional[bytes] = None,
  50. ) -> None:
  51. """
  52. Initializes a basic exception.
  53. @type code: L{bytes} or L{int}
  54. @param code: Refers to an HTTP status code (for example, 200) either as
  55. an integer or a bytestring representing such. If no C{message} is
  56. given, C{code} is mapped to a descriptive bytestring that is used
  57. instead.
  58. @type message: L{bytes}
  59. @param message: A short error message, for example C{b"NOT FOUND"}.
  60. @type response: L{bytes}
  61. @param response: A complete HTML document for an error page.
  62. """
  63. message = message or _codeToMessage(code)
  64. Exception.__init__(self, code, message, response)
  65. if isinstance(code, int):
  66. # If we're given an int, convert it to a bytestring
  67. # downloadPage gives a bytes, Agent gives an int, and it worked by
  68. # accident previously, so just make it keep working.
  69. code = b"%d" % (code,)
  70. elif len(code) != 3 or not code.isdigit():
  71. # Status codes must be 3 digits. See
  72. # https://httpwg.org/specs/rfc9110.html#status.code.extensibility
  73. raise ValueError(f"Not a valid HTTP status code: {code!r}")
  74. self.status = code
  75. self.message = message
  76. self.response = response
  77. def __str__(self) -> str:
  78. s = self.status
  79. if self.message:
  80. s += b" " + self.message
  81. return nativeString(s)
  82. class PageRedirect(Error):
  83. """
  84. A request resulted in an HTTP redirect.
  85. @ivar location: The location of the redirect which was not followed.
  86. """
  87. location: Optional[bytes]
  88. def __init__(
  89. self,
  90. code: Union[int, bytes],
  91. message: Optional[bytes] = None,
  92. response: Optional[bytes] = None,
  93. location: Optional[bytes] = None,
  94. ) -> None:
  95. """
  96. Initializes a page redirect exception.
  97. @type code: L{bytes}
  98. @param code: Refers to an HTTP status code, for example
  99. C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a
  100. descriptive string that is used instead.
  101. @type message: L{bytes}
  102. @param message: A short error message, for example C{b"NOT FOUND"}.
  103. @type response: L{bytes}
  104. @param response: A complete HTML document for an error page.
  105. @type location: L{bytes}
  106. @param location: The location response-header field value. It is an
  107. absolute URI used to redirect the receiver to a location other than
  108. the Request-URI so the request can be completed.
  109. """
  110. Error.__init__(self, code, message, response)
  111. if self.message and location:
  112. self.message = self.message + b" to " + location
  113. self.location = location
  114. class InfiniteRedirection(Error):
  115. """
  116. HTTP redirection is occurring endlessly.
  117. @ivar location: The first URL in the series of redirections which was
  118. not followed.
  119. """
  120. location: Optional[bytes]
  121. def __init__(
  122. self,
  123. code: Union[int, bytes],
  124. message: Optional[bytes] = None,
  125. response: Optional[bytes] = None,
  126. location: Optional[bytes] = None,
  127. ) -> None:
  128. """
  129. Initializes an infinite redirection exception.
  130. @param code: Refers to an HTTP status code, for example
  131. C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to a
  132. descriptive string that is used instead.
  133. @param message: A short error message, for example C{b"NOT FOUND"}.
  134. @param response: A complete HTML document for an error page.
  135. @param location: The location response-header field value. It is an
  136. absolute URI used to redirect the receiver to a location other than
  137. the Request-URI so the request can be completed.
  138. """
  139. Error.__init__(self, code, message, response)
  140. if self.message and location:
  141. self.message = self.message + b" to " + location
  142. self.location = location
  143. class RedirectWithNoLocation(Error):
  144. """
  145. Exception passed to L{ResponseFailed} if we got a redirect without a
  146. C{Location} header field.
  147. @type uri: L{bytes}
  148. @ivar uri: The URI which failed to give a proper location header
  149. field.
  150. @since: 11.1
  151. """
  152. message: bytes
  153. uri: bytes
  154. def __init__(self, code: Union[bytes, int], message: bytes, uri: bytes) -> None:
  155. """
  156. Initializes a page redirect exception when no location is given.
  157. @type code: L{bytes}
  158. @param code: Refers to an HTTP status code, for example
  159. C{http.NOT_FOUND}. If no C{message} is given, C{code} is mapped to
  160. a descriptive string that is used instead.
  161. @type message: L{bytes}
  162. @param message: A short error message.
  163. @type uri: L{bytes}
  164. @param uri: The URI which failed to give a proper location header
  165. field.
  166. """
  167. Error.__init__(self, code, message)
  168. self.message = self.message + b" to " + uri
  169. self.uri = uri
  170. class UnsupportedMethod(Exception):
  171. """
  172. Raised by a resource when faced with a strange request method.
  173. RFC 2616 (HTTP 1.1) gives us two choices when faced with this situation:
  174. If the type of request is known to us, but not allowed for the requested
  175. resource, respond with NOT_ALLOWED. Otherwise, if the request is something
  176. we don't know how to deal with in any case, respond with NOT_IMPLEMENTED.
  177. When this exception is raised by a Resource's render method, the server
  178. will make the appropriate response.
  179. This exception's first argument MUST be a sequence of the methods the
  180. resource *does* support.
  181. """
  182. allowedMethods = ()
  183. def __init__(self, allowedMethods, *args):
  184. Exception.__init__(self, allowedMethods, *args)
  185. self.allowedMethods = allowedMethods
  186. if not isinstance(allowedMethods, Sequence):
  187. raise TypeError(
  188. "First argument must be a sequence of supported methods, "
  189. "but my first argument is not a sequence."
  190. )
  191. def __str__(self) -> str:
  192. return f"Expected one of {self.allowedMethods!r}"
  193. class SchemeNotSupported(Exception):
  194. """
  195. The scheme of a URI was not one of the supported values.
  196. """
  197. class RenderError(Exception):
  198. """
  199. Base exception class for all errors which can occur during template
  200. rendering.
  201. """
  202. class MissingRenderMethod(RenderError):
  203. """
  204. Tried to use a render method which does not exist.
  205. @ivar element: The element which did not have the render method.
  206. @ivar renderName: The name of the renderer which could not be found.
  207. """
  208. def __init__(self, element, renderName):
  209. RenderError.__init__(self, element, renderName)
  210. self.element = element
  211. self.renderName = renderName
  212. def __repr__(self) -> str:
  213. return "{!r}: {!r} had no render method named {!r}".format(
  214. self.__class__.__name__,
  215. self.element,
  216. self.renderName,
  217. )
  218. class MissingTemplateLoader(RenderError):
  219. """
  220. L{MissingTemplateLoader} is raised when trying to render an Element without
  221. a template loader, i.e. a C{loader} attribute.
  222. @ivar element: The Element which did not have a document factory.
  223. """
  224. def __init__(self, element):
  225. RenderError.__init__(self, element)
  226. self.element = element
  227. def __repr__(self) -> str:
  228. return f"{self.__class__.__name__!r}: {self.element!r} had no loader"
  229. class UnexposedMethodError(Exception):
  230. """
  231. Raised on any attempt to get a method which has not been exposed.
  232. """
  233. class UnfilledSlot(Exception):
  234. """
  235. During flattening, a slot with no associated data was encountered.
  236. """
  237. class UnsupportedType(Exception):
  238. """
  239. During flattening, an object of a type which cannot be flattened was
  240. encountered.
  241. """
  242. class ExcessiveBufferingError(Exception):
  243. """
  244. The HTTP/2 protocol has been forced to buffer an excessive amount of
  245. outbound data, and has therefore closed the connection and dropped all
  246. outbound data.
  247. """
  248. class FlattenerError(Exception):
  249. """
  250. An error occurred while flattening an object.
  251. @ivar _roots: A list of the objects on the flattener's stack at the time
  252. the unflattenable object was encountered. The first element is least
  253. deeply nested object and the last element is the most deeply nested.
  254. """
  255. def __init__(self, exception, roots, traceback):
  256. self._exception = exception
  257. self._roots = roots
  258. self._traceback = traceback
  259. Exception.__init__(self, exception, roots, traceback)
  260. def _formatRoot(self, obj):
  261. """
  262. Convert an object from C{self._roots} to a string suitable for
  263. inclusion in a render-traceback (like a normal Python traceback, but
  264. can include "frame" source locations which are not in Python source
  265. files).
  266. @param obj: Any object which can be a render step I{root}.
  267. Typically, L{Tag}s, strings, and other simple Python types.
  268. @return: A string representation of C{obj}.
  269. @rtype: L{str}
  270. """
  271. # There's a circular dependency between this class and 'Tag', although
  272. # only for an isinstance() check.
  273. from twisted.web.template import Tag
  274. if isinstance(obj, (bytes, str)):
  275. # It's somewhat unlikely that there will ever be a str in the roots
  276. # list. However, something like a MemoryError during a str.replace
  277. # call (eg, replacing " with ") could possibly cause this.
  278. # Likewise, UTF-8 encoding a unicode string to a byte string might
  279. # fail like this.
  280. if len(obj) > 40:
  281. if isinstance(obj, str):
  282. ellipsis = "<...>"
  283. else:
  284. ellipsis = b"<...>"
  285. return ascii(obj[:20] + ellipsis + obj[-20:])
  286. else:
  287. return ascii(obj)
  288. elif isinstance(obj, Tag):
  289. if obj.filename is None:
  290. return "Tag <" + obj.tagName + ">"
  291. else:
  292. return 'File "%s", line %d, column %d, in "%s"' % (
  293. obj.filename,
  294. obj.lineNumber,
  295. obj.columnNumber,
  296. obj.tagName,
  297. )
  298. else:
  299. return ascii(obj)
  300. def __repr__(self) -> str:
  301. """
  302. Present a string representation which includes a template traceback, so
  303. we can tell where this error occurred in the template, as well as in
  304. Python.
  305. """
  306. # Avoid importing things unnecessarily until we actually need them;
  307. # since this is an 'error' module we should be extra paranoid about
  308. # that.
  309. from traceback import format_list
  310. if self._roots:
  311. roots = (
  312. " " + "\n ".join([self._formatRoot(r) for r in self._roots]) + "\n"
  313. )
  314. else:
  315. roots = ""
  316. if self._traceback:
  317. traceback = (
  318. "\n".join(
  319. [
  320. line
  321. for entry in format_list(self._traceback)
  322. for line in entry.splitlines()
  323. ]
  324. )
  325. + "\n"
  326. )
  327. else:
  328. traceback = ""
  329. return cast(
  330. str,
  331. (
  332. "Exception while flattening:\n"
  333. + roots
  334. + traceback
  335. + self._exception.__class__.__name__
  336. + ": "
  337. + str(self._exception)
  338. + "\n"
  339. ),
  340. )
  341. def __str__(self) -> str:
  342. return repr(self)
  343. class UnsupportedSpecialHeader(Exception):
  344. """
  345. A HTTP/2 request was received that contained a HTTP/2 pseudo-header field
  346. that is not recognised by Twisted.
  347. """