Merge pull request #2350 from davidism/errorhandler
Before adoption: this commit came in with the history the project adopted, so no landing records it.
show nice message when registering error handler for unknown code
authored by David Lord · committed by GitHub · parents 9049755, 859d9a9 · 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
Provenance
- Commit
c7f433c- Tree
99de1e3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9049755- Parent 2
859d9a9
3 files changed+79 added−54 removed
modified:docs/errorhandling.rst+47 added-24 removed
74 unmodified lines75 76 You might want to show custom error pages to the user when an error occurs.77 This can be done by registering error handlers.78 79-Error handlers are normal :ref:`views` but instead of being registered for80-routes, they are registered for exceptions that are raised while trying to81-do something else.79+An error handler is a normal view function that return a response, but instead80+of being registered for a route, it is registered for an exception or HTTP81+status code that would is raised while trying to handle a request.82 83 Registering84 ```````````85 86-Register error handlers using :meth:`~flask.Flask.errorhandler` or87-:meth:`~flask.Flask.register_error_handler`::86+Register handlers by decorating a function with87+:meth:`~flask.Flask.errorhandler`. Or use88+:meth:`~flask.Flask.register_error_handler` to register the function later.89+Remember to set the error code when returning the response. ::90 91 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):91- return 'bad request!'93+ return 'bad request!', 40094 95+ # or, without the decorator93- app.register_error_handler(400, lambda e: 'bad request!')96+ app.register_error_handler(400, handle_bad_request)97 95-Those two ways are equivalent, but the first one is more clear and leaves96-you 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 codes99-are interchangeable when handed to the registration methods or decorator100-(``BadRequest.code == 400``).99+:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100+when registering handlers. (``BadRequest.code == 400``)101 102-You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103-or HTTP status codes but can register a handler for every exception class you104-like.102+Non-standard HTTP codes cannot be registered by code because they are not known103+by Werkzeug. Instead, define a subclass of104+:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105+register and raise that exception class. ::106 106-.. versionchanged:: 0.11107+ class InsufficientStorage(werkzeug.exceptions.HTTPException):108+ code = 507109+ description = 'Not enough storage space.'110 108- 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)112 113+ raise InsufficientStorage()114+115+Handlers can be registered for any exception class, not just116+:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117+codes. Handlers can be registered for a specific class, or for all subclasses118+of a parent class.119+120 Handling121 ````````122 114-Once an exception instance is raised, its class hierarchy is traversed,115-and searched for in the exception classes for which handlers are registered.116-The most specific handler is selected.123+When an exception is caught by Flask while handling a request, it is first124+looked up by code. If no handler is registered for the code, it is looked up125+by its class hierarchy; the most specific handler is chosen. If no handler is126+registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127+generic message about their code, while other exceptions are converted to a128+generic 500 Internal Server Error.129 118-E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler130+For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler131 is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120-the more specific :exc:`ConnectionRefusedError` handler is called on the121-exception instance, and its response is shown to the user.132+the more specific :exc:`ConnectionRefusedError` handler is called with the133+exception instance to generate the response.134 135+Handlers registered on the blueprint take precedence over those registered136+globally on the application, assuming a blueprint is handling the request that137+raises the exception. However, the blueprint cannot handle 404 routing errors138+because the 404 occurs at the routing level before the blueprint can be139+determined.140+141+.. versionchanged:: 0.11142+143+ Handlers are prioritized by specificity of the exception classes they are144+ registered for instead of the order they are registered in.145+146 Error Mails147 -----------148 149 If the application runs in production mode (which it will do on your268 unmodified linesmodified:flask/app.py+25 added-30 removed
1164 unmodified lines1165 return exc_class, None1166 1167 @setupmethod1168 def errorhandler(self, code_or_exception):1169+ """Register a function to handle errors by code or exception class.1170+1169- """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::1173 1174 @app.errorhandler(404)1175 def page_not_found(error):4 unmodified lines1180 @app.errorhandler(DatabaseError)1181 def special_exception_handler(error):1182 return 'Database connection failed', 5001183 1182- You can also register a function as error handler without using1183- the :meth:`errorhandler` decorator. The following example is1184- equivalent to the one above::1185-1186- def page_not_found(error):1187- return 'This page does not exist', 4041188- app.error_handler_spec[None][404] = page_not_found1189-1190- 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.1193-1194- The first ``None`` refers to the active blueprint. If the error1195- handler should be application wide ``None`` shall be used.1196-1184 .. versionadded:: 0.71185 Use :meth:`register_error_handler` instead of modifying1186 :attr:`error_handler_spec` directly, for application wide error1187 handlers.10 unmodified lines1198 self._register_error_handler(None, code_or_exception, f)1199 return f1200 return decorator1201 1202+ @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 lines1217 :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+ )1225 1226+ 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+ )1233 1234 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1235 handlers[exc_class] = f1236 96 unmodified lines1333 1334 @setupmethod1335 def before_request(self, f):1336 """Registers a function to run before each request.1342- 1337+1338 For example, this can be used to open a database connection, or to load1339 the logged in user from the session.1340 1341 The function will be called without any arguments. If it returns a119 unmodified lines1461 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- 1465+1466 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- 1470+1471 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 lines1537 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- 1541+1542 .. versionchanged:: 1.01543 Bad request errors are not trapped by default in debug mode.1544 1545 .. versionadded:: 0.8231 unmodified lines1777 1778 ``str`` (``unicode`` in Python 2)1779 A response object is created with the string encoded to UTF-81780 as the body.1786- 1781+1782 ``bytes`` (``str`` in Python 2)1783 A response object is created with the bytes as the body.1789- 1784+1785 ``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- 1793+1794 :attr:`response_class`1795 The object is returned unchanged.1801- 1796+1797 other :class:`~werkzeug.wrappers.Response` class1798 The object is coerced to :attr:`response_class`.1804- 1799+1800 :func:`callable`1801 The function is called as a WSGI application. The result is1802 used to create a response object.1803 128 unmodified lines1932 """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- 1936+1937 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 linesmodified:tests/test_basic.py+7 added
868 unmodified lines869 assert rv.status_code == 403870 assert b'forbidden' == rv.data871 872 873+def test_error_handler_unknown_code(app):874+ with pytest.raises(KeyError) as exc_info:875+ app.register_error_handler(999, lambda e: ('999', 999))876+877+ assert 'Use a subclass' in exc_info.value.args[0]878+879+880 def test_error_handling_processing(app, client):881 app.config['LOGGER_HANDLER_POLICY'] = 'never'882 app.testing = False883 946 unmodified lines