error.py 12 KB

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