Skip to content
Myr

show nice message when registering error handler for unknown code

Before adoption: this commit came in with the history the project adopted, so no landing records it.

clean up error handler docs closes #1837

authored by David Lord · committed by David Lord · parent 9049755 · Browse files · 3 files+79 added−54 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+79 added−54 removed

  • tests:+7 added−0 removed
  • other:+72 added−54 removed

3 files+79 added−54 removed

modified:docs/errorhandling.rst+47 added-24 removed
74 unmodified lines
7576You might want to show custom error pages to the user when an error occurs.77This can be done by registering error handlers.7879Error handlers are normal :ref:`views` but instead of being registered for80routes, they are registered for exceptions that are raised while trying to81do something else.79An error handler is a normal view function that return a response, but instead80of being registered for a route, it is registered for an exception or HTTP81status code that would is raised while trying to handle a request.8283Registering84```````````8586Register error handlers using :meth:`~flask.Flask.errorhandler` or87:meth:`~flask.Flask.register_error_handler`::86Register handlers by decorating a function with87:meth:`~flask.Flask.errorhandler`. Or use88:meth:`~flask.Flask.register_error_handler` to register the function later.89Remember to set the error code when returning the response. ::9091 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):91 return 'bad request!'93 return 'bad request!', 4009495 # or, without the decorator93 app.register_error_handler(400, lambda e: 'bad request!')96 app.register_error_handler(400, handle_bad_request)9795Those two ways are equivalent, but the first one is more clear and leaves96you with a function to call on your whim (and in tests). Note that98:exc:`werkzeug.exceptions.HTTPException` subclasses like98:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes99are interchangeable when handed to the registration methods or decorator100(``BadRequest.code == 400``).99:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100when registering handlers. (``BadRequest.code == 400``)101102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.102Non-standard HTTP codes cannot be registered by code because they are not known103by Werkzeug. Instead, define a subclass of104:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105register and raise that exception class. ::106106.. versionchanged:: 0.11107 class InsufficientStorage(werkzeug.exceptions.HTTPException):108 code = 507109 description = 'Not enough storage space.'110108 Errorhandlers are now prioritized by specificity of the exception classes109 they are registered for instead of the order they are registered in.111 app.register_error_handler(InsuffcientStorage, handle_507)112113 raise InsufficientStorage()114115Handlers can be registered for any exception class, not just116:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117codes. Handlers can be registered for a specific class, or for all subclasses118of a parent class.119120Handling121````````122114Once an exception instance is raised, its class hierarchy is traversed,115and searched for in the exception classes for which handlers are registered.116The most specific handler is selected.123When an exception is caught by Flask while handling a request, it is first124looked up by code. If no handler is registered for the code, it is looked up125by its class hierarchy; the most specific handler is chosen. If no handler is126registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127generic message about their code, while other exceptions are converted to a128generic 500 Internal Server Error.129118E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler130For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler131is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120the more specific :exc:`ConnectionRefusedError` handler is called on the121exception instance, and its response is shown to the user.132the more specific :exc:`ConnectionRefusedError` handler is called with the133exception instance to generate the response.134135Handlers registered on the blueprint take precedence over those registered136globally on the application, assuming a blueprint is handling the request that137raises the exception. However, the blueprint cannot handle 404 routing errors138because the 404 occurs at the routing level before the blueprint can be139determined.140141.. versionchanged:: 0.11142143 Handlers are prioritized by specificity of the exception classes they are144 registered for instead of the order they are registered in.145146Error Mails147-----------148149If the application runs in production mode (which it will do on your
268 unmodified lines
modified:flask/app.py+25 added-30 removed
1164 unmodified lines
1165 return exc_class, None11661167 @setupmethod1168 def errorhandler(self, code_or_exception):1169 """Register a function to handle errors by code or exception class.11701169 """A decorator that is used to register a function given an1171 A decorator that is used to register a function given an1172 error code. Example::11731174 @app.errorhandler(404)1175 def page_not_found(error):
4 unmodified lines
1180 @app.errorhandler(DatabaseError)1181 def special_exception_handler(error):1182 return 'Database connection failed', 50011831182 You can also register a function as error handler without using1183 the :meth:`errorhandler` decorator. The following example is1184 equivalent to the one above::11851186 def page_not_found(error):1187 return 'This page does not exist', 4041188 app.error_handler_spec[None][404] = page_not_found11891190 Setting error handlers via assignments to :attr:`error_handler_spec`1191 however is discouraged as it requires fiddling with nested dictionaries1192 and the special case for arbitrary exception types.11931194 The first ``None`` refers to the active blueprint. If the error1195 handler should be application wide ``None`` shall be used.11961184 .. versionadded:: 0.71185 Use :meth:`register_error_handler` instead of modifying1186 :attr:`error_handler_spec` directly, for application wide error1187 handlers.
10 unmodified lines
1198 self._register_error_handler(None, code_or_exception, f)1199 return f1200 return decorator12011202 @setupmethod1203 def register_error_handler(self, code_or_exception, f):1204 """Alternative error attach function to the :meth:`errorhandler`1205 decorator that is more straightforward to use for non decorator1206 usage.
10 unmodified lines
1217 :type f: callable1218 """1219 if isinstance(code_or_exception, HTTPException): # old broken behavior1220 raise ValueError(1233 'Tried to register a handler for an exception instance {0!r}. '1234 'Handlers can only be registered for exception classes or HTTP error codes.'1235 .format(code_or_exception))1221 'Tried to register a handler for an exception instance {0!r}.'1222 ' Handlers can only be registered for exception classes or'1223 ' HTTP error codes.'.format(code_or_exception)1224 )12251226 try:1237 exc_class, code = self._get_exc_class_and_code(code_or_exception)1227 exc_class, code = self._get_exc_class_and_code(code_or_exception)1228 except KeyError:1229 raise KeyError(1230 "'{0}' is not a recognized HTTP error code. Use a subclass of"1231 " HTTPException with that code instead.".format(code_or_exception)1232 )12331234 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1235 handlers[exc_class] = f1236
96 unmodified lines
13331334 @setupmethod1335 def before_request(self, f):1336 """Registers a function to run before each request.1342 13371338 For example, this can be used to open a database connection, or to load1339 the logged in user from the session.13401341 The function will be called without any arguments. If it returns a
119 unmodified lines
1461 def url_value_preprocessor(self, f):1462 """Register a URL value preprocessor function for all view1463 functions in the application. These functions will be called before the1464 :meth:`before_request` functions.1470 14651466 The function can modify the values captured from the matched url before1467 they are passed to the view. For example, this can be used to pop a1468 common language code value and place it in ``g`` rather than pass it to1469 every view.1475 14701471 The function is passed the endpoint name and values dict. The return1472 value is ignored.1473 """1474 self.url_value_preprocessors.setdefault(None, []).append(f)
62 unmodified lines
1537 If it returns ``True`` for any exception the error handler for this1538 exception is not called and it shows up as regular exception in the1539 traceback. This is helpful for debugging implicitly raised HTTP1540 exceptions.1546 15411542 .. versionchanged:: 1.01543 Bad request errors are not trapped by default in debug mode.15441545 .. versionadded:: 0.8
231 unmodified lines
17771778 ``str`` (``unicode`` in Python 2)1779 A response object is created with the string encoded to UTF-81780 as the body.1786 17811782 ``bytes`` (``str`` in Python 2)1783 A response object is created with the bytes as the body.1789 17841785 ``tuple``1786 Either ``(body, status, headers)``, ``(body, status)``, or1787 ``(body, headers)``, where ``body`` is any of the other types1788 allowed here, ``status`` is a string or an integer, and1789 ``headers`` is a dictionary or a list of ``(key, value)``1790 tuples. If ``body`` is a :attr:`response_class` instance,1791 ``status`` overwrites the exiting value and ``headers`` are1792 extended.1798 17931794 :attr:`response_class`1795 The object is returned unchanged.1801 17961797 other :class:`~werkzeug.wrappers.Response` class1798 The object is coerced to :attr:`response_class`.1804 17991800 :func:`callable`1801 The function is called as a WSGI application. The result is1802 used to create a response object.1803
128 unmodified lines
1932 """Called before the request is dispatched. Calls1933 :attr:`url_value_preprocessors` registered with the app and the1934 current blueprint (if any). Then calls :attr:`before_request_funcs`1935 registered with the app and the blueprint.1941 19361937 If any :meth:`before_request` handler returns a non-None value, the1938 value is handled as if it was the return value from the view, and1939 further request handling is stopped.1940 """
195 unmodified lines
modified:tests/test_basic.py+7 added
868 unmodified lines
869 assert rv.status_code == 403870 assert b'forbidden' == rv.data871872873def test_error_handler_unknown_code(app):874 with pytest.raises(KeyError) as exc_info:875 app.register_error_handler(999, lambda e: ('999', 999))876877 assert 'Use a subclass' in exc_info.value.args[0]878879880def test_error_handling_processing(app, client):881 app.config['LOGGER_HANDLER_POLICY'] = 'never'882 app.testing = False883
946 unmodified lines