httpexceptions.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. # (c) 2005 Ian Bicking, Clark C. Evans and contributors
  4. # This module is part of the Python Paste Project and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. # Some of this code was funded by http://prometheusresearch.com
  7. """
  8. HTTP Exception Middleware
  9. This module processes Python exceptions that relate to HTTP exceptions
  10. by defining a set of exceptions, all subclasses of HTTPException, and a
  11. request handler (`middleware`) that catches these exceptions and turns
  12. them into proper responses.
  13. This module defines exceptions according to RFC 2068 [1]_ : codes with
  14. 100-300 are not really errors; 400's are client errors, and 500's are
  15. server errors. According to the WSGI specification [2]_ , the application
  16. can call ``start_response`` more then once only under two conditions:
  17. (a) the response has not yet been sent, or (b) if the second and
  18. subsequent invocations of ``start_response`` have a valid ``exc_info``
  19. argument obtained from ``sys.exc_info()``. The WSGI specification then
  20. requires the server or gateway to handle the case where content has been
  21. sent and then an exception was encountered.
  22. Exceptions in the 5xx range and those raised after ``start_response``
  23. has been called are treated as serious errors and the ``exc_info`` is
  24. filled-in with information needed for a lower level module to generate a
  25. stack trace and log information.
  26. Exception
  27. HTTPException
  28. HTTPRedirection
  29. * 300 - HTTPMultipleChoices
  30. * 301 - HTTPMovedPermanently
  31. * 302 - HTTPFound
  32. * 303 - HTTPSeeOther
  33. * 304 - HTTPNotModified
  34. * 305 - HTTPUseProxy
  35. * 306 - Unused (not implemented, obviously)
  36. * 307 - HTTPTemporaryRedirect
  37. HTTPError
  38. HTTPClientError
  39. * 400 - HTTPBadRequest
  40. * 401 - HTTPUnauthorized
  41. * 402 - HTTPPaymentRequired
  42. * 403 - HTTPForbidden
  43. * 404 - HTTPNotFound
  44. * 405 - HTTPMethodNotAllowed
  45. * 406 - HTTPNotAcceptable
  46. * 407 - HTTPProxyAuthenticationRequired
  47. * 408 - HTTPRequestTimeout
  48. * 409 - HTTPConfict
  49. * 410 - HTTPGone
  50. * 411 - HTTPLengthRequired
  51. * 412 - HTTPPreconditionFailed
  52. * 413 - HTTPRequestEntityTooLarge
  53. * 414 - HTTPRequestURITooLong
  54. * 415 - HTTPUnsupportedMediaType
  55. * 416 - HTTPRequestRangeNotSatisfiable
  56. * 417 - HTTPExpectationFailed
  57. HTTPServerError
  58. * 500 - HTTPInternalServerError
  59. * 501 - HTTPNotImplemented
  60. * 502 - HTTPBadGateway
  61. * 503 - HTTPServiceUnavailable
  62. * 504 - HTTPGatewayTimeout
  63. * 505 - HTTPVersionNotSupported
  64. References:
  65. .. [1] http://www.python.org/peps/pep-0333.html#error-handling
  66. .. [2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5
  67. """
  68. import six
  69. from paste.wsgilib import catch_errors_app
  70. from paste.response import has_header, header_value, replace_header
  71. from paste.request import resolve_relative_url
  72. from paste.util.quoting import strip_html, html_quote, no_quote, comment_quote
  73. SERVER_NAME = 'WSGI Server'
  74. TEMPLATE = """\
  75. <html>\r
  76. <head><title>%(title)s</title></head>\r
  77. <body>\r
  78. <h1>%(title)s</h1>\r
  79. <p>%(body)s</p>\r
  80. <hr noshade>\r
  81. <div align="right">%(server)s</div>\r
  82. </body>\r
  83. </html>\r
  84. """
  85. class HTTPException(Exception):
  86. """
  87. the HTTP exception base class
  88. This encapsulates an HTTP response that interrupts normal application
  89. flow; but one which is not necessarly an error condition. For
  90. example, codes in the 300's are exceptions in that they interrupt
  91. normal processing; however, they are not considered errors.
  92. This class is complicated by 4 factors:
  93. 1. The content given to the exception may either be plain-text or
  94. as html-text.
  95. 2. The template may want to have string-substitutions taken from
  96. the current ``environ`` or values from incoming headers. This
  97. is especially troublesome due to case sensitivity.
  98. 3. The final output may either be text/plain or text/html
  99. mime-type as requested by the client application.
  100. 4. Each exception has a default explanation, but those who
  101. raise exceptions may want to provide additional detail.
  102. Attributes:
  103. ``code``
  104. the HTTP status code for the exception
  105. ``title``
  106. remainder of the status line (stuff after the code)
  107. ``explanation``
  108. a plain-text explanation of the error message that is
  109. not subject to environment or header substitutions;
  110. it is accessible in the template via %(explanation)s
  111. ``detail``
  112. a plain-text message customization that is not subject
  113. to environment or header substitutions; accessible in
  114. the template via %(detail)s
  115. ``template``
  116. a content fragment (in HTML) used for environment and
  117. header substitution; the default template includes both
  118. the explanation and further detail provided in the
  119. message
  120. ``required_headers``
  121. a sequence of headers which are required for proper
  122. construction of the exception
  123. Parameters:
  124. ``detail``
  125. a plain-text override of the default ``detail``
  126. ``headers``
  127. a list of (k,v) header pairs
  128. ``comment``
  129. a plain-text additional information which is
  130. usually stripped/hidden for end-users
  131. To override the template (which is HTML content) or the plain-text
  132. explanation, one must subclass the given exception; or customize it
  133. after it has been created. This particular breakdown of a message
  134. into explanation, detail and template allows both the creation of
  135. plain-text and html messages for various clients as well as
  136. error-free substitution of environment variables and headers.
  137. """
  138. code = None
  139. title = None
  140. explanation = ''
  141. detail = ''
  142. comment = ''
  143. template = "%(explanation)s\r\n<br/>%(detail)s\r\n<!-- %(comment)s -->"
  144. required_headers = ()
  145. def __init__(self, detail=None, headers=None, comment=None):
  146. assert self.code, "Do not directly instantiate abstract exceptions."
  147. assert isinstance(headers, (type(None), list)), (
  148. "headers must be None or a list: %r"
  149. % headers)
  150. assert isinstance(detail, (type(None), six.binary_type, six.text_type)), (
  151. "detail must be None or a string: %r" % detail)
  152. assert isinstance(comment, (type(None), six.binary_type, six.text_type)), (
  153. "comment must be None or a string: %r" % comment)
  154. self.headers = headers or tuple()
  155. for req in self.required_headers:
  156. assert headers and has_header(headers, req), (
  157. "Exception %s must be passed the header %r "
  158. "(got headers: %r)"
  159. % (self.__class__.__name__, req, headers))
  160. if detail is not None:
  161. self.detail = detail
  162. if comment is not None:
  163. self.comment = comment
  164. Exception.__init__(self,"%s %s\n%s\n%s\n" % (
  165. self.code, self.title, self.explanation, self.detail))
  166. def make_body(self, environ, template, escfunc, comment_escfunc=None):
  167. comment_escfunc = comment_escfunc or escfunc
  168. args = {'explanation': escfunc(self.explanation),
  169. 'detail': escfunc(self.detail),
  170. 'comment': comment_escfunc(self.comment)}
  171. if HTTPException.template != self.template:
  172. for (k, v) in environ.items():
  173. args[k] = escfunc(v)
  174. if self.headers:
  175. for (k, v) in self.headers:
  176. args[k.lower()] = escfunc(v)
  177. if six.PY2:
  178. for key, value in args.items():
  179. if isinstance(value, six.text_type):
  180. args[key] = value.encode('utf8', 'xmlcharrefreplace')
  181. return template % args
  182. def plain(self, environ):
  183. """ text/plain representation of the exception """
  184. body = self.make_body(environ, strip_html(self.template), no_quote, comment_quote)
  185. return ('%s %s\r\n%s\r\n' % (self.code, self.title, body))
  186. def html(self, environ):
  187. """ text/html representation of the exception """
  188. body = self.make_body(environ, self.template, html_quote, comment_quote)
  189. return TEMPLATE % {
  190. 'title': self.title,
  191. 'code': self.code,
  192. 'server': SERVER_NAME,
  193. 'body': body }
  194. def prepare_content(self, environ):
  195. if self.headers:
  196. headers = list(self.headers)
  197. else:
  198. headers = []
  199. if 'html' in environ.get('HTTP_ACCEPT','') or \
  200. '*/*' in environ.get('HTTP_ACCEPT',''):
  201. replace_header(headers, 'content-type', 'text/html')
  202. content = self.html(environ)
  203. else:
  204. replace_header(headers, 'content-type', 'text/plain')
  205. content = self.plain(environ)
  206. if isinstance(content, six.text_type):
  207. content = content.encode('utf8')
  208. cur_content_type = (
  209. header_value(headers, 'content-type')
  210. or 'text/html')
  211. replace_header(
  212. headers, 'content-type',
  213. cur_content_type + '; charset=utf8')
  214. return headers, content
  215. def response(self, environ):
  216. from paste.wsgiwrappers import WSGIResponse
  217. headers, content = self.prepare_content(environ)
  218. resp = WSGIResponse(code=self.code, content=content)
  219. resp.headers = resp.headers.fromlist(headers)
  220. return resp
  221. def wsgi_application(self, environ, start_response, exc_info=None):
  222. """
  223. This exception as a WSGI application
  224. """
  225. headers, content = self.prepare_content(environ)
  226. start_response('%s %s' % (self.code, self.title),
  227. headers,
  228. exc_info)
  229. return [content]
  230. __call__ = wsgi_application
  231. def __repr__(self):
  232. return '<%s %s; code=%s>' % (self.__class__.__name__,
  233. self.title, self.code)
  234. class HTTPError(HTTPException):
  235. """
  236. base class for status codes in the 400's and 500's
  237. This is an exception which indicates that an error has occurred,
  238. and that any work in progress should not be committed. These are
  239. typically results in the 400's and 500's.
  240. """
  241. #
  242. # 3xx Redirection
  243. #
  244. # This class of status code indicates that further action needs to be
  245. # taken by the user agent in order to fulfill the request. The action
  246. # required MAY be carried out by the user agent without interaction with
  247. # the user if and only if the method used in the second request is GET or
  248. # HEAD. A client SHOULD detect infinite redirection loops, since such
  249. # loops generate network traffic for each redirection.
  250. #
  251. class HTTPRedirection(HTTPException):
  252. """
  253. base class for 300's status code (redirections)
  254. This is an abstract base class for 3xx redirection. It indicates
  255. that further action needs to be taken by the user agent in order
  256. to fulfill the request. It does not necessarly signal an error
  257. condition.
  258. """
  259. class _HTTPMove(HTTPRedirection):
  260. """
  261. redirections which require a Location field
  262. Since a 'Location' header is a required attribute of 301, 302, 303,
  263. 305 and 307 (but not 304), this base class provides the mechanics to
  264. make this easy. While this has the same parameters as HTTPException,
  265. if a location is not provided in the headers; it is assumed that the
  266. detail _is_ the location (this for backward compatibility, otherwise
  267. we'd add a new attribute).
  268. """
  269. required_headers = ('location',)
  270. explanation = 'The resource has been moved to'
  271. template = (
  272. '%(explanation)s <a href="%(location)s">%(location)s</a>;\r\n'
  273. 'you should be redirected automatically.\r\n'
  274. '%(detail)s\r\n<!-- %(comment)s -->')
  275. def __init__(self, detail=None, headers=None, comment=None):
  276. assert isinstance(headers, (type(None), list))
  277. headers = headers or []
  278. location = header_value(headers,'location')
  279. if not location:
  280. location = detail
  281. detail = ''
  282. headers.append(('location', location))
  283. assert location, ("HTTPRedirection specified neither a "
  284. "location in the headers nor did it "
  285. "provide a detail argument.")
  286. HTTPRedirection.__init__(self, location, headers, comment)
  287. if detail is not None:
  288. self.detail = detail
  289. def relative_redirect(cls, dest_uri, environ, detail=None, headers=None, comment=None):
  290. """
  291. Create a redirect object with the dest_uri, which may be relative,
  292. considering it relative to the uri implied by the given environ.
  293. """
  294. location = resolve_relative_url(dest_uri, environ)
  295. headers = headers or []
  296. headers.append(('Location', location))
  297. return cls(detail=detail, headers=headers, comment=comment)
  298. relative_redirect = classmethod(relative_redirect)
  299. def location(self):
  300. for name, value in self.headers:
  301. if name.lower() == 'location':
  302. return value
  303. else:
  304. raise KeyError("No location set for %s" % self)
  305. class HTTPMultipleChoices(_HTTPMove):
  306. code = 300
  307. title = 'Multiple Choices'
  308. class HTTPMovedPermanently(_HTTPMove):
  309. code = 301
  310. title = 'Moved Permanently'
  311. class HTTPFound(_HTTPMove):
  312. code = 302
  313. title = 'Found'
  314. explanation = 'The resource was found at'
  315. # This one is safe after a POST (the redirected location will be
  316. # retrieved with GET):
  317. class HTTPSeeOther(_HTTPMove):
  318. code = 303
  319. title = 'See Other'
  320. class HTTPNotModified(HTTPRedirection):
  321. # @@: but not always (HTTP section 14.18.1)...?
  322. # @@: Removed 'date' requirement, as its not required for an ETag
  323. # @@: FIXME: This should require either an ETag or a date header
  324. code = 304
  325. title = 'Not Modified'
  326. message = ''
  327. # @@: should include date header, optionally other headers
  328. # @@: should not return a content body
  329. def plain(self, environ):
  330. return ''
  331. def html(self, environ):
  332. """ text/html representation of the exception """
  333. return ''
  334. class HTTPUseProxy(_HTTPMove):
  335. # @@: OK, not a move, but looks a little like one
  336. code = 305
  337. title = 'Use Proxy'
  338. explanation = (
  339. 'The resource must be accessed through a proxy '
  340. 'located at')
  341. class HTTPTemporaryRedirect(_HTTPMove):
  342. code = 307
  343. title = 'Temporary Redirect'
  344. #
  345. # 4xx Client Error
  346. #
  347. # The 4xx class of status code is intended for cases in which the client
  348. # seems to have erred. Except when responding to a HEAD request, the
  349. # server SHOULD include an entity containing an explanation of the error
  350. # situation, and whether it is a temporary or permanent condition. These
  351. # status codes are applicable to any request method. User agents SHOULD
  352. # display any included entity to the user.
  353. #
  354. class HTTPClientError(HTTPError):
  355. """
  356. base class for the 400's, where the client is in-error
  357. This is an error condition in which the client is presumed to be
  358. in-error. This is an expected problem, and thus is not considered
  359. a bug. A server-side traceback is not warranted. Unless specialized,
  360. this is a '400 Bad Request'
  361. """
  362. code = 400
  363. title = 'Bad Request'
  364. explanation = ('The server could not comply with the request since\r\n'
  365. 'it is either malformed or otherwise incorrect.\r\n')
  366. class HTTPBadRequest(HTTPClientError):
  367. pass
  368. class HTTPUnauthorized(HTTPClientError):
  369. code = 401
  370. title = 'Unauthorized'
  371. explanation = (
  372. 'This server could not verify that you are authorized to\r\n'
  373. 'access the document you requested. Either you supplied the\r\n'
  374. 'wrong credentials (e.g., bad password), or your browser\r\n'
  375. 'does not understand how to supply the credentials required.\r\n')
  376. class HTTPPaymentRequired(HTTPClientError):
  377. code = 402
  378. title = 'Payment Required'
  379. explanation = ('Access was denied for financial reasons.')
  380. class HTTPForbidden(HTTPClientError):
  381. code = 403
  382. title = 'Forbidden'
  383. explanation = ('Access was denied to this resource.')
  384. class HTTPNotFound(HTTPClientError):
  385. code = 404
  386. title = 'Not Found'
  387. explanation = ('The resource could not be found.')
  388. class HTTPMethodNotAllowed(HTTPClientError):
  389. required_headers = ('allow',)
  390. code = 405
  391. title = 'Method Not Allowed'
  392. # override template since we need an environment variable
  393. template = ('The method %(REQUEST_METHOD)s is not allowed for '
  394. 'this resource.\r\n%(detail)s')
  395. class HTTPNotAcceptable(HTTPClientError):
  396. code = 406
  397. title = 'Not Acceptable'
  398. # override template since we need an environment variable
  399. template = ('The resource could not be generated that was '
  400. 'acceptable to your browser (content\r\nof type '
  401. '%(HTTP_ACCEPT)s).\r\n%(detail)s')
  402. class HTTPProxyAuthenticationRequired(HTTPClientError):
  403. code = 407
  404. title = 'Proxy Authentication Required'
  405. explanation = ('Authentication /w a local proxy is needed.')
  406. class HTTPRequestTimeout(HTTPClientError):
  407. code = 408
  408. title = 'Request Timeout'
  409. explanation = ('The server has waited too long for the request to '
  410. 'be sent by the client.')
  411. class HTTPConflict(HTTPClientError):
  412. code = 409
  413. title = 'Conflict'
  414. explanation = ('There was a conflict when trying to complete '
  415. 'your request.')
  416. class HTTPGone(HTTPClientError):
  417. code = 410
  418. title = 'Gone'
  419. explanation = ('This resource is no longer available. No forwarding '
  420. 'address is given.')
  421. class HTTPLengthRequired(HTTPClientError):
  422. code = 411
  423. title = 'Length Required'
  424. explanation = ('Content-Length header required.')
  425. class HTTPPreconditionFailed(HTTPClientError):
  426. code = 412
  427. title = 'Precondition Failed'
  428. explanation = ('Request precondition failed.')
  429. class HTTPRequestEntityTooLarge(HTTPClientError):
  430. code = 413
  431. title = 'Request Entity Too Large'
  432. explanation = ('The body of your request was too large for this server.')
  433. class HTTPRequestURITooLong(HTTPClientError):
  434. code = 414
  435. title = 'Request-URI Too Long'
  436. explanation = ('The request URI was too long for this server.')
  437. class HTTPUnsupportedMediaType(HTTPClientError):
  438. code = 415
  439. title = 'Unsupported Media Type'
  440. # override template since we need an environment variable
  441. template = ('The request media type %(CONTENT_TYPE)s is not '
  442. 'supported by this server.\r\n%(detail)s')
  443. class HTTPRequestRangeNotSatisfiable(HTTPClientError):
  444. code = 416
  445. title = 'Request Range Not Satisfiable'
  446. explanation = ('The Range requested is not available.')
  447. class HTTPExpectationFailed(HTTPClientError):
  448. code = 417
  449. title = 'Expectation Failed'
  450. explanation = ('Expectation failed.')
  451. #
  452. # 5xx Server Error
  453. #
  454. # Response status codes beginning with the digit "5" indicate cases in
  455. # which the server is aware that it has erred or is incapable of
  456. # performing the request. Except when responding to a HEAD request, the
  457. # server SHOULD include an entity containing an explanation of the error
  458. # situation, and whether it is a temporary or permanent condition. User
  459. # agents SHOULD display any included entity to the user. These response
  460. # codes are applicable to any request method.
  461. #
  462. class HTTPServerError(HTTPError):
  463. """
  464. base class for the 500's, where the server is in-error
  465. This is an error condition in which the server is presumed to be
  466. in-error. This is usually unexpected, and thus requires a traceback;
  467. ideally, opening a support ticket for the customer. Unless specialized,
  468. this is a '500 Internal Server Error'
  469. """
  470. code = 500
  471. title = 'Internal Server Error'
  472. explanation = (
  473. 'The server has either erred or is incapable of performing\r\n'
  474. 'the requested operation.\r\n')
  475. class HTTPInternalServerError(HTTPServerError):
  476. pass
  477. class HTTPNotImplemented(HTTPServerError):
  478. code = 501
  479. title = 'Not Implemented'
  480. # override template since we need an environment variable
  481. template = ('The request method %(REQUEST_METHOD)s is not implemented '
  482. 'for this server.\r\n%(detail)s')
  483. class HTTPBadGateway(HTTPServerError):
  484. code = 502
  485. title = 'Bad Gateway'
  486. explanation = ('Bad gateway.')
  487. class HTTPServiceUnavailable(HTTPServerError):
  488. code = 503
  489. title = 'Service Unavailable'
  490. explanation = ('The server is currently unavailable. '
  491. 'Please try again at a later time.')
  492. class HTTPGatewayTimeout(HTTPServerError):
  493. code = 504
  494. title = 'Gateway Timeout'
  495. explanation = ('The gateway has timed out.')
  496. class HTTPVersionNotSupported(HTTPServerError):
  497. code = 505
  498. title = 'HTTP Version Not Supported'
  499. explanation = ('The HTTP version is not supported.')
  500. # abstract HTTP related exceptions
  501. __all__ = ['HTTPException', 'HTTPRedirection', 'HTTPError' ]
  502. _exceptions = {}
  503. for name, value in six.iteritems(dict(globals())):
  504. if (isinstance(value, (type, six.class_types)) and
  505. issubclass(value, HTTPException) and
  506. value.code):
  507. _exceptions[value.code] = value
  508. __all__.append(name)
  509. def get_exception(code):
  510. return _exceptions[code]
  511. ############################################################
  512. ## Middleware implementation:
  513. ############################################################
  514. class HTTPExceptionHandler(object):
  515. """
  516. catches exceptions and turns them into proper HTTP responses
  517. This middleware catches any exceptions (which are subclasses of
  518. ``HTTPException``) and turns them into proper HTTP responses.
  519. Note if the headers have already been sent, the stack trace is
  520. always maintained as this indicates a programming error.
  521. Note that you must raise the exception before returning the
  522. app_iter, and you cannot use this with generator apps that don't
  523. raise an exception until after their app_iter is iterated over.
  524. """
  525. def __init__(self, application, warning_level=None):
  526. assert not warning_level or ( warning_level > 99 and
  527. warning_level < 600)
  528. if warning_level is not None:
  529. import warnings
  530. warnings.warn('The warning_level parameter is not used or supported',
  531. DeprecationWarning, 2)
  532. self.warning_level = warning_level or 500
  533. self.application = application
  534. def __call__(self, environ, start_response):
  535. environ['paste.httpexceptions'] = self
  536. environ.setdefault('paste.expected_exceptions',
  537. []).append(HTTPException)
  538. try:
  539. return self.application(environ, start_response)
  540. except HTTPException as exc:
  541. return exc(environ, start_response)
  542. def middleware(*args, **kw):
  543. import warnings
  544. # deprecated 13 dec 2005
  545. warnings.warn('httpexceptions.middleware is deprecated; use '
  546. 'make_middleware or HTTPExceptionHandler instead',
  547. DeprecationWarning, 2)
  548. return make_middleware(*args, **kw)
  549. def make_middleware(app, global_conf=None, warning_level=None):
  550. """
  551. ``httpexceptions`` middleware; this catches any
  552. ``paste.httpexceptions.HTTPException`` exceptions (exceptions like
  553. ``HTTPNotFound``, ``HTTPMovedPermanently``, etc) and turns them
  554. into proper HTTP responses.
  555. ``warning_level`` can be an integer corresponding to an HTTP code.
  556. Any code over that value will be passed 'up' the chain, potentially
  557. reported on by another piece of middleware.
  558. """
  559. if warning_level:
  560. warning_level = int(warning_level)
  561. return HTTPExceptionHandler(app, warning_level=warning_level)
  562. __all__.extend(['HTTPExceptionHandler', 'get_exception'])