error.py 12 KB

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