always pass InternalServerError instance to 500 handler
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 2fa30f6 · Browse files · 3 files·+146 added−11 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+146 added−11 removed
- tests:+95 added−2 removed
- other:+51 added−9 removed
Provenance
- Commit
9054f6d- Tree
7c9bd98- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
2fa30f6
3 files changed+146 added−11 removed
modified:src/flask/app.py+40 added-9 removed
1809 unmodified lines1810 reraise(exc_type, exc_value, tb)1811 return handler(e)1812 1813 def handle_exception(self, e):1814- """Default exception handling that kicks in when an exception1815- occurs that is not caught. In debug mode the exception will1816- be re-raised immediately, otherwise it is logged and the handler1817- for a 500 internal server error is used. If no such handler1818- exists, a default 500 internal server error message is displayed.1814+ """Handle an exception that did not have an error handler1815+ associated with it, or that was raised from an error handler.1816+ This always causes a 500 ``InternalServerError``.1817 1818+ Always sends the :data:`got_request_exception` signal.1819+1820+ If :attr:`propagate_exceptions` is ``True``, such as in debug1821+ mode, the error will be re-raised so that the debugger can1822+ display it. Otherwise, the original exception is logged, and1823+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.1824+1825+ If an error handler is registered for ``InternalServerError`` or1826+ ``500``, it will be used. For consistency, the handler will1827+ always receive the ``InternalServerError``. The original1828+ unhandled exception is available as ``e.original_exception``.1829+1830+ .. note::1831+ Prior to Werkzeug 1.0.0, ``InternalServerError`` will not1832+ always have a ``original_exception`` attribute. Use1833+ ``getattr(e, "original_exception", None)`` to simulate the1834+ behavior for compatibility.1835+1836+ .. versionchanged:: 1.1.01837+ Always passes the ``InternalServerError`` instance to the1838+ handler, setting ``original_exception`` to the unhandled1839+ error.1840+1841+ .. versionchanged:: 1.1.01842+ ``after_request`` functions and other finalization is done1843+ even for the default 500 response when there is no handler.1844+1845 .. versionadded:: 0.31846 """1847 exc_type, exc_value, tb = sys.exc_info()1848 got_request_exception.send(self, exception=e)8 unmodified lines1857 else:1858 raise e1859 1860 self.log_exception((exc_type, exc_value, tb))1836- handler = self._find_error_handler(InternalServerError())1837- if handler is None:1838- return InternalServerError()1839- return self.finalize_request(handler(e), from_error_handler=True)1861+ server_error = InternalServerError()1862+ # TODO: pass as param when Werkzeug>=1.0.0 is required1863+ # TODO: also remove note about this from docstring and docs1864+ server_error.original_exception = e1865+ handler = self._find_error_handler(server_error)1866 1867+ if handler is not None:1868+ server_error = handler(server_error)1869+1870+ return self.finalize_request(server_error, from_error_handler=True)1871+1872 def log_exception(self, exc_info):1873 """Logs an exception. This is called by :meth:`handle_exception`1874 if debugging is disabled and right before the handler is called.1875 The default implementation logs the exception as error on the581 unmodified linesmodified:tests/test_user_error_handler.py+95 added-2 removed
4 unmodified lines5 6 :copyright: © 2010 by the Pallets team.7 :license: BSD, see LICENSE for more details.8 """9+import pytest10 from werkzeug.exceptions import Forbidden11 from werkzeug.exceptions import HTTPException12 from werkzeug.exceptions import InternalServerError13 from werkzeug.exceptions import NotFound11 unmodified lines25 return "custom"26 27 @app.errorhandler(500)28 def handle_500(e):28- return type(e).__name__29+ assert isinstance(e, InternalServerError)30+ original = getattr(e, "original_exception", None)31 32+ if original is not None:33+ return "wrapped " + type(original).__name__34+35+ return "direct"36+37 @app.route("/custom")38 def custom_test():39 raise CustomException()40 41 @app.route("/keyerror")42 def key_error():43 raise KeyError()44 45+ @app.route("/abort")46+ def do_abort():47+ flask.abort(500)48+49 app.testing = False50 assert client.get("/custom").data == b"custom"40- assert client.get("/keyerror").data == b"KeyError"51+ assert client.get("/keyerror").data == b"wrapped KeyError"52+ assert client.get("/abort").data == b"direct"53 54 55 def test_error_handler_subclass(app):56 class ParentException(Exception):148 unmodified lines205 assert c.get("/undefined").data == b"default"206 assert c.get("/forbidden").data == b"forbidden"207 # Don't handle RequestRedirect raised when adding slash.208 assert c.get("/slash", follow_redirects=True).data == b"slash"209+210+211+class TestGenericHandlers(object):212+ """Test how very generic handlers are dispatched to."""213+214+ class Custom(Exception):215+ pass216+217+ @pytest.fixture()218+ def app(self, app):219+ @app.route("/custom")220+ def do_custom():221+ raise self.Custom()222+223+ @app.route("/error")224+ def do_error():225+ raise KeyError()226+227+ @app.route("/abort")228+ def do_abort():229+ flask.abort(500)230+231+ @app.route("/raise")232+ def do_raise():233+ raise InternalServerError()234+235+ app.config["PROPAGATE_EXCEPTIONS"] = False236+ return app237+238+ def report_error(self, e):239+ original = getattr(e, "original_exception", None)240+241+ if original is not None:242+ return "wrapped " + type(original).__name__243+244+ return "direct " + type(e).__name__245+246+ @pytest.mark.parametrize("to_handle", (InternalServerError, 500))247+ def test_handle_class_or_code(self, app, client, to_handle):248+ """``InternalServerError`` and ``500`` are aliases, they should249+ have the same behavior. Both should only receive250+ ``InternalServerError``, which might wrap another error.251+ """252+253+ @app.errorhandler(to_handle)254+ def handle_500(e):255+ assert isinstance(e, InternalServerError)256+ return self.report_error(e)257+258+ assert client.get("/custom").data == b"wrapped Custom"259+ assert client.get("/error").data == b"wrapped KeyError"260+ assert client.get("/abort").data == b"direct InternalServerError"261+ assert client.get("/raise").data == b"direct InternalServerError"262+263+ def test_handle_generic_http(self, app, client):264+ """``HTTPException`` should only receive ``HTTPException``265+ subclasses. It will receive ``404`` routing exceptions.266+ """267+268+ @app.errorhandler(HTTPException)269+ def handle_http(e):270+ assert isinstance(e, HTTPException)271+ return str(e.code)272+273+ assert client.get("/error").data == b"500"274+ assert client.get("/abort").data == b"500"275+ assert client.get("/not-found").data == b"404"276+277+ def test_handle_generic(self, app, client):278+ """Generic ``Exception`` will handle all exceptions directly,279+ including ``HTTPExceptions``.280+ """281+282+ @app.errorhandler(Exception)283+ def handle_exception(e):284+ return self.report_error(e)285+286+ assert client.get("/custom").data == b"direct Custom"287+ assert client.get("/error").data == b"direct KeyError"288+ assert client.get("/abort").data == b"direct InternalServerError"289+ assert client.get("/not-found").data == b"direct NotFound"modified:CHANGES.rst+11 added
9 unmodified lines10 Unreleased11 12 - Bump minimum Werkzeug version to >= 0.15.13 - Drop support for Python 3.4.14+- Error handlers for ``InternalServerError`` or ``500`` will always be15+ passed an instance of ``InternalServerError``. If they are invoked16+ due to an unhandled exception, that original exception is now17+ available as ``e.original_exception`` rather than being passed18+ directly to the handler. The same is true if the handler is for the19+ base ``HTTPException``.This makes error handler behavior more20+ consistent. :pr:`3266`21+22+ - :meth:`Flask.finalize_request` is called for all unhandled23+ exceptions even if there is no ``500`` error handler.24+25 - :meth:`flask.RequestContext.copy` includes the current session26 object in the request context copy. This prevents ``session``27 pointing to an out-of-date object. (`#2935`_)28 - Using built-in RequestContext, unprintable Unicode characters in1011 unmodified lines