exceptions.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.exceptions
  4. ~~~~~~~~~~~~~~~~~~~
  5. This module implements a number of Python exceptions you can raise from
  6. within your views to trigger a standard non-200 response.
  7. Usage Example
  8. -------------
  9. ::
  10. from werkzeug.wrappers import BaseRequest
  11. from werkzeug.wsgi import responder
  12. from werkzeug.exceptions import HTTPException, NotFound
  13. def view(request):
  14. raise NotFound()
  15. @responder
  16. def application(environ, start_response):
  17. request = BaseRequest(environ)
  18. try:
  19. return view(request)
  20. except HTTPException as e:
  21. return e
  22. As you can see from this example those exceptions are callable WSGI
  23. applications. Because of Python 2.4 compatibility those do not extend
  24. from the response objects but only from the python exception class.
  25. As a matter of fact they are not Werkzeug response objects. However you
  26. can get a response object by calling ``get_response()`` on a HTTP
  27. exception.
  28. Keep in mind that you have to pass an environment to ``get_response()``
  29. because some errors fetch additional information from the WSGI
  30. environment.
  31. If you want to hook in a different exception page to say, a 404 status
  32. code, you can add a second except for a specific subclass of an error::
  33. @responder
  34. def application(environ, start_response):
  35. request = BaseRequest(environ)
  36. try:
  37. return view(request)
  38. except NotFound, e:
  39. return not_found(request)
  40. except HTTPException, e:
  41. return e
  42. :copyright: 2007 Pallets
  43. :license: BSD-3-Clause
  44. """
  45. import sys
  46. from datetime import datetime
  47. from ._compat import implements_to_string
  48. from ._compat import integer_types
  49. from ._compat import iteritems
  50. from ._compat import text_type
  51. from ._internal import _get_environ
  52. from .utils import escape
  53. @implements_to_string
  54. class HTTPException(Exception):
  55. """Baseclass for all HTTP exceptions. This exception can be called as WSGI
  56. application to render a default error page or you can catch the subclasses
  57. of it independently and render nicer error messages.
  58. """
  59. code = None
  60. description = None
  61. def __init__(self, description=None, response=None):
  62. super(HTTPException, self).__init__()
  63. if description is not None:
  64. self.description = description
  65. self.response = response
  66. @classmethod
  67. def wrap(cls, exception, name=None):
  68. """Create an exception that is a subclass of the calling HTTP
  69. exception and the ``exception`` argument.
  70. The first argument to the class will be passed to the
  71. wrapped ``exception``, the rest to the HTTP exception. If
  72. ``e.args`` is not empty and ``e.show_exception`` is ``True``,
  73. the wrapped exception message is added to the HTTP error
  74. description.
  75. .. versionchanged:: 0.15.5
  76. The ``show_exception`` attribute controls whether the
  77. description includes the wrapped exception message.
  78. .. versionchanged:: 0.15.0
  79. The description includes the wrapped exception message.
  80. """
  81. class newcls(cls, exception):
  82. _description = cls.description
  83. show_exception = False
  84. def __init__(self, arg=None, *args, **kwargs):
  85. super(cls, self).__init__(*args, **kwargs)
  86. if arg is None:
  87. exception.__init__(self)
  88. else:
  89. exception.__init__(self, arg)
  90. @property
  91. def description(self):
  92. if self.show_exception:
  93. return "{}\n{}: {}".format(
  94. self._description, exception.__name__, exception.__str__(self)
  95. )
  96. return self._description
  97. @description.setter
  98. def description(self, value):
  99. self._description = value
  100. newcls.__module__ = sys._getframe(1).f_globals.get("__name__")
  101. name = name or cls.__name__ + exception.__name__
  102. newcls.__name__ = newcls.__qualname__ = name
  103. return newcls
  104. @property
  105. def name(self):
  106. """The status name."""
  107. from .http import HTTP_STATUS_CODES
  108. return HTTP_STATUS_CODES.get(self.code, "Unknown Error")
  109. def get_description(self, environ=None):
  110. """Get the description."""
  111. return u"<p>%s</p>" % escape(self.description).replace("\n", "<br>")
  112. def get_body(self, environ=None):
  113. """Get the HTML body."""
  114. return text_type(
  115. (
  116. u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
  117. u"<title>%(code)s %(name)s</title>\n"
  118. u"<h1>%(name)s</h1>\n"
  119. u"%(description)s\n"
  120. )
  121. % {
  122. "code": self.code,
  123. "name": escape(self.name),
  124. "description": self.get_description(environ),
  125. }
  126. )
  127. def get_headers(self, environ=None):
  128. """Get a list of headers."""
  129. return [("Content-Type", "text/html; charset=utf-8")]
  130. def get_response(self, environ=None):
  131. """Get a response object. If one was passed to the exception
  132. it's returned directly.
  133. :param environ: the optional environ for the request. This
  134. can be used to modify the response depending
  135. on how the request looked like.
  136. :return: a :class:`Response` object or a subclass thereof.
  137. """
  138. from .wrappers.response import Response
  139. if self.response is not None:
  140. return self.response
  141. if environ is not None:
  142. environ = _get_environ(environ)
  143. headers = self.get_headers(environ)
  144. return Response(self.get_body(environ), self.code, headers)
  145. def __call__(self, environ, start_response):
  146. """Call the exception as WSGI application.
  147. :param environ: the WSGI environment.
  148. :param start_response: the response callable provided by the WSGI
  149. server.
  150. """
  151. response = self.get_response(environ)
  152. return response(environ, start_response)
  153. def __str__(self):
  154. code = self.code if self.code is not None else "???"
  155. return "%s %s: %s" % (code, self.name, self.description)
  156. def __repr__(self):
  157. code = self.code if self.code is not None else "???"
  158. return "<%s '%s: %s'>" % (self.__class__.__name__, code, self.name)
  159. class BadRequest(HTTPException):
  160. """*400* `Bad Request`
  161. Raise if the browser sends something to the application the application
  162. or server cannot handle.
  163. """
  164. code = 400
  165. description = (
  166. "The browser (or proxy) sent a request that this server could "
  167. "not understand."
  168. )
  169. class ClientDisconnected(BadRequest):
  170. """Internal exception that is raised if Werkzeug detects a disconnected
  171. client. Since the client is already gone at that point attempting to
  172. send the error message to the client might not work and might ultimately
  173. result in another exception in the server. Mainly this is here so that
  174. it is silenced by default as far as Werkzeug is concerned.
  175. Since disconnections cannot be reliably detected and are unspecified
  176. by WSGI to a large extent this might or might not be raised if a client
  177. is gone.
  178. .. versionadded:: 0.8
  179. """
  180. class SecurityError(BadRequest):
  181. """Raised if something triggers a security error. This is otherwise
  182. exactly like a bad request error.
  183. .. versionadded:: 0.9
  184. """
  185. class BadHost(BadRequest):
  186. """Raised if the submitted host is badly formatted.
  187. .. versionadded:: 0.11.2
  188. """
  189. class Unauthorized(HTTPException):
  190. """*401* ``Unauthorized``
  191. Raise if the user is not authorized to access a resource.
  192. The ``www_authenticate`` argument should be used to set the
  193. ``WWW-Authenticate`` header. This is used for HTTP basic auth and
  194. other schemes. Use :class:`~werkzeug.datastructures.WWWAuthenticate`
  195. to create correctly formatted values. Strictly speaking a 401
  196. response is invalid if it doesn't provide at least one value for
  197. this header, although real clients typically don't care.
  198. :param description: Override the default message used for the body
  199. of the response.
  200. :param www-authenticate: A single value, or list of values, for the
  201. WWW-Authenticate header.
  202. .. versionchanged:: 0.15.3
  203. If the ``www_authenticate`` argument is not set, the
  204. ``WWW-Authenticate`` header is not set.
  205. .. versionchanged:: 0.15.3
  206. The ``response`` argument was restored.
  207. .. versionchanged:: 0.15.1
  208. ``description`` was moved back as the first argument, restoring
  209. its previous position.
  210. .. versionchanged:: 0.15.0
  211. ``www_authenticate`` was added as the first argument, ahead of
  212. ``description``.
  213. """
  214. code = 401
  215. description = (
  216. "The server could not verify that you are authorized to access"
  217. " the URL requested. You either supplied the wrong credentials"
  218. " (e.g. a bad password), or your browser doesn't understand"
  219. " how to supply the credentials required."
  220. )
  221. def __init__(self, description=None, response=None, www_authenticate=None):
  222. HTTPException.__init__(self, description, response)
  223. if www_authenticate is not None:
  224. if not isinstance(www_authenticate, (tuple, list)):
  225. www_authenticate = (www_authenticate,)
  226. self.www_authenticate = www_authenticate
  227. def get_headers(self, environ=None):
  228. headers = HTTPException.get_headers(self, environ)
  229. if self.www_authenticate:
  230. headers.append(
  231. ("WWW-Authenticate", ", ".join([str(x) for x in self.www_authenticate]))
  232. )
  233. return headers
  234. class Forbidden(HTTPException):
  235. """*403* `Forbidden`
  236. Raise if the user doesn't have the permission for the requested resource
  237. but was authenticated.
  238. """
  239. code = 403
  240. description = (
  241. "You don't have the permission to access the requested"
  242. " resource. It is either read-protected or not readable by the"
  243. " server."
  244. )
  245. class NotFound(HTTPException):
  246. """*404* `Not Found`
  247. Raise if a resource does not exist and never existed.
  248. """
  249. code = 404
  250. description = (
  251. "The requested URL was not found on the server. If you entered"
  252. " the URL manually please check your spelling and try again."
  253. )
  254. class MethodNotAllowed(HTTPException):
  255. """*405* `Method Not Allowed`
  256. Raise if the server used a method the resource does not handle. For
  257. example `POST` if the resource is view only. Especially useful for REST.
  258. The first argument for this exception should be a list of allowed methods.
  259. Strictly speaking the response would be invalid if you don't provide valid
  260. methods in the header which you can do with that list.
  261. """
  262. code = 405
  263. description = "The method is not allowed for the requested URL."
  264. def __init__(self, valid_methods=None, description=None):
  265. """Takes an optional list of valid http methods
  266. starting with werkzeug 0.3 the list will be mandatory."""
  267. HTTPException.__init__(self, description)
  268. self.valid_methods = valid_methods
  269. def get_headers(self, environ=None):
  270. headers = HTTPException.get_headers(self, environ)
  271. if self.valid_methods:
  272. headers.append(("Allow", ", ".join(self.valid_methods)))
  273. return headers
  274. class NotAcceptable(HTTPException):
  275. """*406* `Not Acceptable`
  276. Raise if the server can't return any content conforming to the
  277. `Accept` headers of the client.
  278. """
  279. code = 406
  280. description = (
  281. "The resource identified by the request is only capable of"
  282. " generating response entities which have content"
  283. " characteristics not acceptable according to the accept"
  284. " headers sent in the request."
  285. )
  286. class RequestTimeout(HTTPException):
  287. """*408* `Request Timeout`
  288. Raise to signalize a timeout.
  289. """
  290. code = 408
  291. description = (
  292. "The server closed the network connection because the browser"
  293. " didn't finish the request within the specified time."
  294. )
  295. class Conflict(HTTPException):
  296. """*409* `Conflict`
  297. Raise to signal that a request cannot be completed because it conflicts
  298. with the current state on the server.
  299. .. versionadded:: 0.7
  300. """
  301. code = 409
  302. description = (
  303. "A conflict happened while processing the request. The"
  304. " resource might have been modified while the request was being"
  305. " processed."
  306. )
  307. class Gone(HTTPException):
  308. """*410* `Gone`
  309. Raise if a resource existed previously and went away without new location.
  310. """
  311. code = 410
  312. description = (
  313. "The requested URL is no longer available on this server and"
  314. " there is no forwarding address. If you followed a link from a"
  315. " foreign page, please contact the author of this page."
  316. )
  317. class LengthRequired(HTTPException):
  318. """*411* `Length Required`
  319. Raise if the browser submitted data but no ``Content-Length`` header which
  320. is required for the kind of processing the server does.
  321. """
  322. code = 411
  323. description = (
  324. "A request with this method requires a valid <code>Content-"
  325. "Length</code> header."
  326. )
  327. class PreconditionFailed(HTTPException):
  328. """*412* `Precondition Failed`
  329. Status code used in combination with ``If-Match``, ``If-None-Match``, or
  330. ``If-Unmodified-Since``.
  331. """
  332. code = 412
  333. description = (
  334. "The precondition on the request for the URL failed positive evaluation."
  335. )
  336. class RequestEntityTooLarge(HTTPException):
  337. """*413* `Request Entity Too Large`
  338. The status code one should return if the data submitted exceeded a given
  339. limit.
  340. """
  341. code = 413
  342. description = "The data value transmitted exceeds the capacity limit."
  343. class RequestURITooLarge(HTTPException):
  344. """*414* `Request URI Too Large`
  345. Like *413* but for too long URLs.
  346. """
  347. code = 414
  348. description = (
  349. "The length of the requested URL exceeds the capacity limit for"
  350. " this server. The request cannot be processed."
  351. )
  352. class UnsupportedMediaType(HTTPException):
  353. """*415* `Unsupported Media Type`
  354. The status code returned if the server is unable to handle the media type
  355. the client transmitted.
  356. """
  357. code = 415
  358. description = (
  359. "The server does not support the media type transmitted in the request."
  360. )
  361. class RequestedRangeNotSatisfiable(HTTPException):
  362. """*416* `Requested Range Not Satisfiable`
  363. The client asked for an invalid part of the file.
  364. .. versionadded:: 0.7
  365. """
  366. code = 416
  367. description = "The server cannot provide the requested range."
  368. def __init__(self, length=None, units="bytes", description=None):
  369. """Takes an optional `Content-Range` header value based on ``length``
  370. parameter.
  371. """
  372. HTTPException.__init__(self, description)
  373. self.length = length
  374. self.units = units
  375. def get_headers(self, environ=None):
  376. headers = HTTPException.get_headers(self, environ)
  377. if self.length is not None:
  378. headers.append(("Content-Range", "%s */%d" % (self.units, self.length)))
  379. return headers
  380. class ExpectationFailed(HTTPException):
  381. """*417* `Expectation Failed`
  382. The server cannot meet the requirements of the Expect request-header.
  383. .. versionadded:: 0.7
  384. """
  385. code = 417
  386. description = "The server could not meet the requirements of the Expect header"
  387. class ImATeapot(HTTPException):
  388. """*418* `I'm a teapot`
  389. The server should return this if it is a teapot and someone attempted
  390. to brew coffee with it.
  391. .. versionadded:: 0.7
  392. """
  393. code = 418
  394. description = "This server is a teapot, not a coffee machine"
  395. class UnprocessableEntity(HTTPException):
  396. """*422* `Unprocessable Entity`
  397. Used if the request is well formed, but the instructions are otherwise
  398. incorrect.
  399. """
  400. code = 422
  401. description = (
  402. "The request was well-formed but was unable to be followed due"
  403. " to semantic errors."
  404. )
  405. class Locked(HTTPException):
  406. """*423* `Locked`
  407. Used if the resource that is being accessed is locked.
  408. """
  409. code = 423
  410. description = "The resource that is being accessed is locked."
  411. class FailedDependency(HTTPException):
  412. """*424* `Failed Dependency`
  413. Used if the method could not be performed on the resource
  414. because the requested action depended on another action and that action failed.
  415. """
  416. code = 424
  417. description = (
  418. "The method could not be performed on the resource because the"
  419. " requested action depended on another action and that action"
  420. " failed."
  421. )
  422. class PreconditionRequired(HTTPException):
  423. """*428* `Precondition Required`
  424. The server requires this request to be conditional, typically to prevent
  425. the lost update problem, which is a race condition between two or more
  426. clients attempting to update a resource through PUT or DELETE. By requiring
  427. each client to include a conditional header ("If-Match" or "If-Unmodified-
  428. Since") with the proper value retained from a recent GET request, the
  429. server ensures that each client has at least seen the previous revision of
  430. the resource.
  431. """
  432. code = 428
  433. description = (
  434. "This request is required to be conditional; try using"
  435. ' "If-Match" or "If-Unmodified-Since".'
  436. )
  437. class _RetryAfter(HTTPException):
  438. """Adds an optional ``retry_after`` parameter which will set the
  439. ``Retry-After`` header. May be an :class:`int` number of seconds or
  440. a :class:`~datetime.datetime`.
  441. """
  442. def __init__(self, description=None, response=None, retry_after=None):
  443. super(_RetryAfter, self).__init__(description, response)
  444. self.retry_after = retry_after
  445. def get_headers(self, environ=None):
  446. headers = super(_RetryAfter, self).get_headers(environ)
  447. if self.retry_after:
  448. if isinstance(self.retry_after, datetime):
  449. from .http import http_date
  450. value = http_date(self.retry_after)
  451. else:
  452. value = str(self.retry_after)
  453. headers.append(("Retry-After", value))
  454. return headers
  455. class TooManyRequests(_RetryAfter):
  456. """*429* `Too Many Requests`
  457. The server is limiting the rate at which this user receives
  458. responses, and this request exceeds that rate. (The server may use
  459. any convenient method to identify users and their request rates).
  460. The server may include a "Retry-After" header to indicate how long
  461. the user should wait before retrying.
  462. :param retry_after: If given, set the ``Retry-After`` header to this
  463. value. May be an :class:`int` number of seconds or a
  464. :class:`~datetime.datetime`.
  465. .. versionchanged:: 1.0
  466. Added ``retry_after`` parameter.
  467. """
  468. code = 429
  469. description = "This user has exceeded an allotted request count. Try again later."
  470. class RequestHeaderFieldsTooLarge(HTTPException):
  471. """*431* `Request Header Fields Too Large`
  472. The server refuses to process the request because the header fields are too
  473. large. One or more individual fields may be too large, or the set of all
  474. headers is too large.
  475. """
  476. code = 431
  477. description = "One or more header fields exceeds the maximum size."
  478. class UnavailableForLegalReasons(HTTPException):
  479. """*451* `Unavailable For Legal Reasons`
  480. This status code indicates that the server is denying access to the
  481. resource as a consequence of a legal demand.
  482. """
  483. code = 451
  484. description = "Unavailable for legal reasons."
  485. class InternalServerError(HTTPException):
  486. """*500* `Internal Server Error`
  487. Raise if an internal server error occurred. This is a good fallback if an
  488. unknown error occurred in the dispatcher.
  489. .. versionchanged:: 1.0.0
  490. Added the :attr:`original_exception` attribute.
  491. """
  492. code = 500
  493. description = (
  494. "The server encountered an internal error and was unable to"
  495. " complete your request. Either the server is overloaded or"
  496. " there is an error in the application."
  497. )
  498. def __init__(self, description=None, response=None, original_exception=None):
  499. #: The original exception that caused this 500 error. Can be
  500. #: used by frameworks to provide context when handling
  501. #: unexpected errors.
  502. self.original_exception = original_exception
  503. super(InternalServerError, self).__init__(
  504. description=description, response=response
  505. )
  506. class NotImplemented(HTTPException):
  507. """*501* `Not Implemented`
  508. Raise if the application does not support the action requested by the
  509. browser.
  510. """
  511. code = 501
  512. description = "The server does not support the action requested by the browser."
  513. class BadGateway(HTTPException):
  514. """*502* `Bad Gateway`
  515. If you do proxying in your application you should return this status code
  516. if you received an invalid response from the upstream server it accessed
  517. in attempting to fulfill the request.
  518. """
  519. code = 502
  520. description = (
  521. "The proxy server received an invalid response from an upstream server."
  522. )
  523. class ServiceUnavailable(_RetryAfter):
  524. """*503* `Service Unavailable`
  525. Status code you should return if a service is temporarily
  526. unavailable.
  527. :param retry_after: If given, set the ``Retry-After`` header to this
  528. value. May be an :class:`int` number of seconds or a
  529. :class:`~datetime.datetime`.
  530. .. versionchanged:: 1.0
  531. Added ``retry_after`` parameter.
  532. """
  533. code = 503
  534. description = (
  535. "The server is temporarily unable to service your request due"
  536. " to maintenance downtime or capacity problems. Please try"
  537. " again later."
  538. )
  539. class GatewayTimeout(HTTPException):
  540. """*504* `Gateway Timeout`
  541. Status code you should return if a connection to an upstream server
  542. times out.
  543. """
  544. code = 504
  545. description = "The connection to an upstream server timed out."
  546. class HTTPVersionNotSupported(HTTPException):
  547. """*505* `HTTP Version Not Supported`
  548. The server does not support the HTTP protocol version used in the request.
  549. """
  550. code = 505
  551. description = (
  552. "The server does not support the HTTP protocol version used in the request."
  553. )
  554. default_exceptions = {}
  555. __all__ = ["HTTPException"]
  556. def _find_exceptions():
  557. for _name, obj in iteritems(globals()):
  558. try:
  559. is_http_exception = issubclass(obj, HTTPException)
  560. except TypeError:
  561. is_http_exception = False
  562. if not is_http_exception or obj.code is None:
  563. continue
  564. __all__.append(obj.__name__)
  565. old_obj = default_exceptions.get(obj.code, None)
  566. if old_obj is not None and issubclass(obj, old_obj):
  567. continue
  568. default_exceptions[obj.code] = obj
  569. _find_exceptions()
  570. del _find_exceptions
  571. class Aborter(object):
  572. """When passed a dict of code -> exception items it can be used as
  573. callable that raises exceptions. If the first argument to the
  574. callable is an integer it will be looked up in the mapping, if it's
  575. a WSGI application it will be raised in a proxy exception.
  576. The rest of the arguments are forwarded to the exception constructor.
  577. """
  578. def __init__(self, mapping=None, extra=None):
  579. if mapping is None:
  580. mapping = default_exceptions
  581. self.mapping = dict(mapping)
  582. if extra is not None:
  583. self.mapping.update(extra)
  584. def __call__(self, code, *args, **kwargs):
  585. if not args and not kwargs and not isinstance(code, integer_types):
  586. raise HTTPException(response=code)
  587. if code not in self.mapping:
  588. raise LookupError("no exception for %r" % code)
  589. raise self.mapping[code](*args, **kwargs)
  590. def abort(status, *args, **kwargs):
  591. """Raises an :py:exc:`HTTPException` for the given status code or WSGI
  592. application.
  593. If a status code is given, it will be looked up in the list of
  594. exceptions and will raise that exception. If passed a WSGI application,
  595. it will wrap it in a proxy WSGI exception and raise that::
  596. abort(404) # 404 Not Found
  597. abort(Response('Hello World'))
  598. """
  599. return _aborter(status, *args, **kwargs)
  600. _aborter = Aborter()
  601. #: An exception that is used to signal both a :exc:`KeyError` and a
  602. #: :exc:`BadRequest`. Used by many of the datastructures.
  603. BadRequestKeyError = BadRequest.wrap(KeyError)