httpexceptions.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 types
  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
  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), basestring)), (
  151. "detail must be None or a string: %r" % detail)
  152. assert isinstance(comment, (type(None), basestring)), (
  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. return template % args
  173. for (k, v) in environ.items():
  174. args[k] = escfunc(v)
  175. if self.headers:
  176. for (k, v) in self.headers:
  177. args[k.lower()] = escfunc(v)
  178. return template % args
  179. def plain(self, environ):
  180. """ text/plain representation of the exception """
  181. body = self.make_body(environ, strip_html(self.template), no_quote)
  182. return ('%s %s\r\n%s\r\n' % (self.code, self.title, body))
  183. def html(self, environ):
  184. """ text/html representation of the exception """
  185. body = self.make_body(environ, self.template, html_quote, no_quote)
  186. return TEMPLATE % {
  187. 'title': self.title,
  188. 'code': self.code,
  189. 'server': SERVER_NAME,
  190. 'body': body }
  191. def prepare_content(self, environ):
  192. if self.headers:
  193. headers = list(self.headers)
  194. else:
  195. headers = []
  196. if 'html' in environ.get('HTTP_ACCEPT','') or \
  197. '*/*' in environ.get('HTTP_ACCEPT',''):
  198. replace_header(headers, 'content-type', 'text/html')
  199. content = self.html(environ)
  200. else:
  201. replace_header(headers, 'content-type', 'text/plain')
  202. content = self.plain(environ)
  203. if isinstance(content, unicode):
  204. content = content.encode('utf8')
  205. cur_content_type = (
  206. header_value(headers, 'content-type')
  207. or 'text/html')
  208. replace_header(
  209. headers, 'content-type',
  210. cur_content_type + '; charset=utf8')
  211. return headers, content
  212. def response(self, environ):
  213. from paste.wsgiwrappers import WSGIResponse
  214. headers, content = self.prepare_content(environ)
  215. resp = WSGIResponse(code=self.code, content=content)
  216. resp.headers = resp.headers.fromlist(headers)
  217. return resp
  218. def wsgi_application(self, environ, start_response, exc_info=None):
  219. """
  220. This exception as a WSGI application
  221. """
  222. headers, content = self.prepare_content(environ)
  223. start_response('%s %s' % (self.code, self.title),
  224. headers,
  225. exc_info)
  226. return [content]
  227. __call__ = wsgi_application
  228. def __repr__(self):
  229. return '<%s %s; code=%s>' % (self.__class__.__name__,
  230. self.title, self.code)
  231. class HTTPError(HTTPException):
  232. """
  233. base class for status codes in the 400's and 500's
  234. This is an exception which indicates that an error has occurred,
  235. and that any work in progress should not be committed. These are
  236. typically results in the 400's and 500's.
  237. """
  238. #
  239. # 3xx Redirection
  240. #
  241. # This class of status code indicates that further action needs to be
  242. # taken by the user agent in order to fulfill the request. The action
  243. # required MAY be carried out by the user agent without interaction with
  244. # the user if and only if the method used in the second request is GET or
  245. # HEAD. A client SHOULD detect infinite redirection loops, since such
  246. # loops generate network traffic for each redirection.
  247. #
  248. class HTTPRedirection(HTTPException):
  249. """
  250. base class for 300's status code (redirections)
  251. This is an abstract base class for 3xx redirection. It indicates
  252. that further action needs to be taken by the user agent in order
  253. to fulfill the request. It does not necessarly signal an error
  254. condition.
  255. """
  256. class _HTTPMove(HTTPRedirection):
  257. """
  258. redirections which require a Location field
  259. Since a 'Location' header is a required attribute of 301, 302, 303,
  260. 305 and 307 (but not 304), this base class provides the mechanics to
  261. make this easy. While this has the same parameters as HTTPException,
  262. if a location is not provided in the headers; it is assumed that the
  263. detail _is_ the location (this for backward compatibility, otherwise
  264. we'd add a new attribute).
  265. """
  266. required_headers = ('location',)
  267. explanation = 'The resource has been moved to'
  268. template = (
  269. '%(explanation)s <a href="%(location)s">%(location)s</a>;\r\n'
  270. 'you should be redirected automatically.\r\n'
  271. '%(detail)s\r\n<!-- %(comment)s -->')
  272. def __init__(self, detail=None, headers=None, comment=None):
  273. assert isinstance(headers, (type(None), list))
  274. headers = headers or []
  275. location = header_value(headers,'location')
  276. if not location:
  277. location = detail
  278. detail = ''
  279. headers.append(('location', location))
  280. assert location, ("HTTPRedirection specified neither a "
  281. "location in the headers nor did it "
  282. "provide a detail argument.")
  283. HTTPRedirection.__init__(self, location, headers, comment)
  284. if detail is not None:
  285. self.detail = detail
  286. def relative_redirect(cls, dest_uri, environ, detail=None, headers=None, comment=None):
  287. """
  288. Create a redirect object with the dest_uri, which may be relative,
  289. considering it relative to the uri implied by the given environ.
  290. """
  291. location = resolve_relative_url(dest_uri, environ)
  292. headers = headers or []
  293. headers.append(('Location', location))
  294. return cls(detail=detail, headers=headers, comment=comment)
  295. relative_redirect = classmethod(relative_redirect)
  296. def location(self):
  297. for name, value in self.headers:
  298. if name.lower() == 'location':
  299. return value
  300. else:
  301. raise KeyError("No location set for %s" % self)
  302. class HTTPMultipleChoices(_HTTPMove):
  303. code = 300
  304. title = 'Multiple Choices'
  305. class HTTPMovedPermanently(_HTTPMove):
  306. code = 301
  307. title = 'Moved Permanently'
  308. class HTTPFound(_HTTPMove):
  309. code = 302
  310. title = 'Found'
  311. explanation = 'The resource was found at'
  312. # This one is safe after a POST (the redirected location will be
  313. # retrieved with GET):
  314. class HTTPSeeOther(_HTTPMove):
  315. code = 303
  316. title = 'See Other'
  317. class HTTPNotModified(HTTPRedirection):
  318. # @@: but not always (HTTP section 14.18.1)...?
  319. # @@: Removed 'date' requirement, as its not required for an ETag
  320. # @@: FIXME: This should require either an ETag or a date header
  321. code = 304
  322. title = 'Not Modified'
  323. message = ''
  324. # @@: should include date header, optionally other headers
  325. # @@: should not return a content body
  326. def plain(self, environ):
  327. return ''
  328. def html(self, environ):
  329. """ text/html representation of the exception """
  330. return ''
  331. class HTTPUseProxy(_HTTPMove):
  332. # @@: OK, not a move, but looks a little like one
  333. code = 305
  334. title = 'Use Proxy'
  335. explanation = (
  336. 'The resource must be accessed through a proxy '
  337. 'located at')
  338. class HTTPTemporaryRedirect(_HTTPMove):
  339. code = 307
  340. title = 'Temporary Redirect'
  341. #
  342. # 4xx Client Error
  343. #
  344. # The 4xx class of status code is intended for cases in which the client
  345. # seems to have erred. Except when responding to a HEAD request, the
  346. # server SHOULD include an entity containing an explanation of the error
  347. # situation, and whether it is a temporary or permanent condition. These
  348. # status codes are applicable to any request method. User agents SHOULD
  349. # display any included entity to the user.
  350. #
  351. class HTTPClientError(HTTPError):
  352. """
  353. base class for the 400's, where the client is in-error
  354. This is an error condition in which the client is presumed to be
  355. in-error. This is an expected problem, and thus is not considered
  356. a bug. A server-side traceback is not warranted. Unless specialized,
  357. this is a '400 Bad Request'
  358. """
  359. code = 400
  360. title = 'Bad Request'
  361. explanation = ('The server could not comply with the request since\r\n'
  362. 'it is either malformed or otherwise incorrect.\r\n')
  363. class HTTPBadRequest(HTTPClientError):
  364. pass
  365. class HTTPUnauthorized(HTTPClientError):
  366. code = 401
  367. title = 'Unauthorized'
  368. explanation = (
  369. 'This server could not verify that you are authorized to\r\n'
  370. 'access the document you requested. Either you supplied the\r\n'
  371. 'wrong credentials (e.g., bad password), or your browser\r\n'
  372. 'does not understand how to supply the credentials required.\r\n')
  373. class HTTPPaymentRequired(HTTPClientError):
  374. code = 402
  375. title = 'Payment Required'
  376. explanation = ('Access was denied for financial reasons.')
  377. class HTTPForbidden(HTTPClientError):
  378. code = 403
  379. title = 'Forbidden'
  380. explanation = ('Access was denied to this resource.')
  381. class HTTPNotFound(HTTPClientError):
  382. code = 404
  383. title = 'Not Found'
  384. explanation = ('The resource could not be found.')
  385. class HTTPMethodNotAllowed(HTTPClientError):
  386. required_headers = ('allow',)
  387. code = 405
  388. title = 'Method Not Allowed'
  389. # override template since we need an environment variable
  390. template = ('The method %(REQUEST_METHOD)s is not allowed for '
  391. 'this resource.\r\n%(detail)s')
  392. class HTTPNotAcceptable(HTTPClientError):
  393. code = 406
  394. title = 'Not Acceptable'
  395. # override template since we need an environment variable
  396. template = ('The resource could not be generated that was '
  397. 'acceptable to your browser (content\r\nof type '
  398. '%(HTTP_ACCEPT)s).\r\n%(detail)s')
  399. class HTTPProxyAuthenticationRequired(HTTPClientError):
  400. code = 407
  401. title = 'Proxy Authentication Required'
  402. explanation = ('Authentication /w a local proxy is needed.')
  403. class HTTPRequestTimeout(HTTPClientError):
  404. code = 408
  405. title = 'Request Timeout'
  406. explanation = ('The server has waited too long for the request to '
  407. 'be sent by the client.')
  408. class HTTPConflict(HTTPClientError):
  409. code = 409
  410. title = 'Conflict'
  411. explanation = ('There was a conflict when trying to complete '
  412. 'your request.')
  413. class HTTPGone(HTTPClientError):
  414. code = 410
  415. title = 'Gone'
  416. explanation = ('This resource is no longer available. No forwarding '
  417. 'address is given.')
  418. class HTTPLengthRequired(HTTPClientError):
  419. code = 411
  420. title = 'Length Required'
  421. explanation = ('Content-Length header required.')
  422. class HTTPPreconditionFailed(HTTPClientError):
  423. code = 412
  424. title = 'Precondition Failed'
  425. explanation = ('Request precondition failed.')
  426. class HTTPRequestEntityTooLarge(HTTPClientError):
  427. code = 413
  428. title = 'Request Entity Too Large'
  429. explanation = ('The body of your request was too large for this server.')
  430. class HTTPRequestURITooLong(HTTPClientError):
  431. code = 414
  432. title = 'Request-URI Too Long'
  433. explanation = ('The request URI was too long for this server.')
  434. class HTTPUnsupportedMediaType(HTTPClientError):
  435. code = 415
  436. title = 'Unsupported Media Type'
  437. # override template since we need an environment variable
  438. template = ('The request media type %(CONTENT_TYPE)s is not '
  439. 'supported by this server.\r\n%(detail)s')
  440. class HTTPRequestRangeNotSatisfiable(HTTPClientError):
  441. code = 416
  442. title = 'Request Range Not Satisfiable'
  443. explanation = ('The Range requested is not available.')
  444. class HTTPExpectationFailed(HTTPClientError):
  445. code = 417
  446. title = 'Expectation Failed'
  447. explanation = ('Expectation failed.')
  448. #
  449. # 5xx Server Error
  450. #
  451. # Response status codes beginning with the digit "5" indicate cases in
  452. # which the server is aware that it has erred or is incapable of
  453. # performing the request. Except when responding to a HEAD request, the
  454. # server SHOULD include an entity containing an explanation of the error
  455. # situation, and whether it is a temporary or permanent condition. User
  456. # agents SHOULD display any included entity to the user. These response
  457. # codes are applicable to any request method.
  458. #
  459. class HTTPServerError(HTTPError):
  460. """
  461. base class for the 500's, where the server is in-error
  462. This is an error condition in which the server is presumed to be
  463. in-error. This is usually unexpected, and thus requires a traceback;
  464. ideally, opening a support ticket for the customer. Unless specialized,
  465. this is a '500 Internal Server Error'
  466. """
  467. code = 500
  468. title = 'Internal Server Error'
  469. explanation = (
  470. 'The server has either erred or is incapable of performing\r\n'
  471. 'the requested operation.\r\n')
  472. class HTTPInternalServerError(HTTPServerError):
  473. pass
  474. class HTTPNotImplemented(HTTPServerError):
  475. code = 501
  476. title = 'Not Implemented'
  477. # override template since we need an environment variable
  478. template = ('The request method %(REQUEST_METHOD)s is not implemented '
  479. 'for this server.\r\n%(detail)s')
  480. class HTTPBadGateway(HTTPServerError):
  481. code = 502
  482. title = 'Bad Gateway'
  483. explanation = ('Bad gateway.')
  484. class HTTPServiceUnavailable(HTTPServerError):
  485. code = 503
  486. title = 'Service Unavailable'
  487. explanation = ('The server is currently unavailable. '
  488. 'Please try again at a later time.')
  489. class HTTPGatewayTimeout(HTTPServerError):
  490. code = 504
  491. title = 'Gateway Timeout'
  492. explanation = ('The gateway has timed out.')
  493. class HTTPVersionNotSupported(HTTPServerError):
  494. code = 505
  495. title = 'HTTP Version Not Supported'
  496. explanation = ('The HTTP version is not supported.')
  497. # abstract HTTP related exceptions
  498. __all__ = ['HTTPException', 'HTTPRedirection', 'HTTPError' ]
  499. _exceptions = {}
  500. for name, value in globals().items():
  501. if (isinstance(value, (type, types.ClassType)) and
  502. issubclass(value, HTTPException) and
  503. value.code):
  504. _exceptions[value.code] = value
  505. __all__.append(name)
  506. def get_exception(code):
  507. return _exceptions[code]
  508. ############################################################
  509. ## Middleware implementation:
  510. ############################################################
  511. class HTTPExceptionHandler(object):
  512. """
  513. catches exceptions and turns them into proper HTTP responses
  514. Attributes:
  515. ``warning_level``
  516. This attribute determines for what exceptions a stack
  517. trace is kept for lower level reporting; by default, it
  518. only keeps stack trace for 5xx, HTTPServerError exceptions.
  519. To keep a stack trace for 4xx, HTTPClientError exceptions,
  520. set this to 400.
  521. This middleware catches any exceptions (which are subclasses of
  522. ``HTTPException``) and turns them into proper HTTP responses.
  523. Note if the headers have already been sent, the stack trace is
  524. always maintained as this indicates a programming error.
  525. Note that you must raise the exception before returning the
  526. app_iter, and you cannot use this with generator apps that don't
  527. raise an exception until after their app_iter is iterated over.
  528. """
  529. def __init__(self, application, warning_level=None):
  530. assert not warning_level or ( warning_level > 99 and
  531. warning_level < 600)
  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, 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'])