Merge pull request #3266 from pallets/internal-server-error-type
Before adoption: this commit came in with the history the project adopted, so no landing records it.
always pass InternalServerError instance to 500 handler
authored by David Lord · committed by GitHub · parents 2fa30f6, 54519ef · Browse files · 4 files·+233 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+233 added−14 removed
- tests:+95 added−2 removed
- other:+138 added−12 removed
Provenance
- Commit
185d7cb- Tree
cb72e65- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
2fa30f6- Parent 2
54519ef
4 files changed+233 added−14 removed
modified:docs/errorhandling.rst+87 added-3 removed
137 unmodified lines138 raises the exception. However, the blueprint cannot handle 404 routing errors139 because the 404 occurs at the routing level before the blueprint can be140 determined.141 142-.. versionchanged:: 0.11142 144- Handlers are prioritized by specificity of the exception classes they are145- registered for instead of the order they are registered in.143+Generic Exception Handlers144+``````````````````````````145 146+It is possible to register error handlers for very generic base classes147+such as ``HTTPException`` or even ``Exception``. However, be aware that148+these will catch more than you might expect.149+150+An error handler for ``HTTPException`` might be useful for turning151+the default HTML errors pages into JSON, for example. However, this152+handler will trigger for things you don't cause directly, such as 404153+and 405 errors during routing. Be sure to craft your handler carefully154+so you don't lose information about the HTTP error.155+156+.. code-block:: python157+158+ from flask import json159+ from werkzeug.exceptions import HTTPException160+161+ @app.errorhandler(HTTPException)162+ def handle_exception(e):163+ """Return JSON instead of HTML for HTTP errors."""164+ # start with the correct headers and status code from the error165+ response = e.get_response()166+ # replace the body with JSON167+ response.data = json.dumps({168+ "code": e.code,169+ "name": e.name,170+ "description": e.description,171+ })172+ response.content_type = "application/json"173+ return response174+175+176+An error handler for ``Exception`` might seem useful for changing how177+all errors, even unhandled ones, are presented to the user. However,178+this is similar to doing ``except Exception:`` in Python, it will179+capture *all* otherwise unhandled errors, including all HTTP status180+codes. In most cases it will be safer to register handlers for more181+specific exceptions. Since ``HTTPException`` instances are valid WSGI182+responses, you could also pass them through directly.183+184+.. code-block:: python185+186+ from werkzeug.exceptions import HTTPException187+188+ @app.errorhandler(Exception)189+ def handle_exception(e):190+ # pass through HTTP errors191+ if isinstance(e, HTTPException):192+ return e193+194+ # now you're handling non-HTTP exceptions only195+ return render_template("500_generic.html", e=e), 500196+197+Error handlers still respect the exception class hierarchy. If you198+register handlers for both ``HTTPException`` and ``Exception``, the199+``Exception`` handler will not handle ``HTTPException`` subclasses200+because it the ``HTTPException`` handler is more specific.201+202+Unhandled Exceptions203+````````````````````204+205+When there is no error handler registered for an exception, a 500206+Internal Server Error will be returned instead. See207+:meth:`flask.Flask.handle_exception` for information about this208+behavior.209+210+If there is an error handler registered for ``InternalServerError``,211+this will be invoked. As of Flask 1.1.0, this error handler will always212+be passed an instance of ``InternalServerError``, not the original213+unhandled error. The original error is available as ``e.original_error``.214+Until Werkzeug 1.0.0, this attribute will only exist during unhandled215+errors, use ``getattr`` to get access it for compatibility.216+217+.. code-block:: python218+219+ @app.errorhandler(InternalServerError)220+ def handle_500(e):221+ original = getattr(e, "original_exception", None)222+223+ if original is None:224+ # direct 500 error, such as abort(500)225+ return render_template("500.html"), 500226+227+ # wrapped unhandled error228+ return render_template("500_unhandled.html", e=original), 500229+230+231 Logging232 -------233 234 See :ref:`logging` for information on how to log exceptions, such as by63 unmodified linesmodified: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 an ``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