Skip to content
Myr

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

4 files+233 added−14 removed

modified:docs/errorhandling.rst+87 added-3 removed
137 unmodified lines
138raises the exception. However, the blueprint cannot handle 404 routing errors139because the 404 occurs at the routing level before the blueprint can be140determined.141142.. versionchanged:: 0.11142144 Handlers are prioritized by specificity of the exception classes they are145 registered for instead of the order they are registered in.143Generic Exception Handlers144``````````````````````````145146It is possible to register error handlers for very generic base classes147such as ``HTTPException`` or even ``Exception``. However, be aware that148these will catch more than you might expect.149150An error handler for ``HTTPException`` might be useful for turning151the default HTML errors pages into JSON, for example. However, this152handler will trigger for things you don't cause directly, such as 404153and 405 errors during routing. Be sure to craft your handler carefully154so you don't lose information about the HTTP error.155156.. code-block:: python157158 from flask import json159 from werkzeug.exceptions import HTTPException160161 @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 response174175176An error handler for ``Exception`` might seem useful for changing how177all errors, even unhandled ones, are presented to the user. However,178this is similar to doing ``except Exception:`` in Python, it will179capture *all* otherwise unhandled errors, including all HTTP status180codes. In most cases it will be safer to register handlers for more181specific exceptions. Since ``HTTPException`` instances are valid WSGI182responses, you could also pass them through directly.183184.. code-block:: python185186 from werkzeug.exceptions import HTTPException187188 @app.errorhandler(Exception)189 def handle_exception(e):190 # pass through HTTP errors191 if isinstance(e, HTTPException):192 return e193194 # now you're handling non-HTTP exceptions only195 return render_template("500_generic.html", e=e), 500196197Error handlers still respect the exception class hierarchy. If you198register handlers for both ``HTTPException`` and ``Exception``, the199``Exception`` handler will not handle ``HTTPException`` subclasses200because it the ``HTTPException`` handler is more specific.201202Unhandled Exceptions203````````````````````204205When there is no error handler registered for an exception, a 500206Internal Server Error will be returned instead. See207:meth:`flask.Flask.handle_exception` for information about this208behavior.209210If there is an error handler registered for ``InternalServerError``,211this will be invoked. As of Flask 1.1.0, this error handler will always212be passed an instance of ``InternalServerError``, not the original213unhandled error. The original error is available as ``e.original_error``.214Until Werkzeug 1.0.0, this attribute will only exist during unhandled215errors, use ``getattr`` to get access it for compatibility.216217.. code-block:: python218219 @app.errorhandler(InternalServerError)220 def handle_500(e):221 original = getattr(e, "original_exception", None)222223 if original is None:224 # direct 500 error, such as abort(500)225 return render_template("500.html"), 500226227 # wrapped unhandled error228 return render_template("500_unhandled.html", e=original), 500229230231Logging232-------233234See :ref:`logging` for information on how to log exceptions, such as by
63 unmodified lines
modified:src/flask/app.py+40 added-9 removed
1809 unmodified lines
1810 reraise(exc_type, exc_value, tb)1811 return handler(e)18121813 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``.18171818 Always sends the :data:`got_request_exception` signal.18191820 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.18241825 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``.18291830 .. 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.18351836 .. versionchanged:: 1.1.01837 Always passes the ``InternalServerError`` instance to the1838 handler, setting ``original_exception`` to the unhandled1839 error.18401841 .. versionchanged:: 1.1.01842 ``after_request`` functions and other finalization is done1843 even for the default 500 response when there is no handler.18441845 .. versionadded:: 0.31846 """1847 exc_type, exc_value, tb = sys.exc_info()1848 got_request_exception.send(self, exception=e)
8 unmodified lines
1857 else:1858 raise e18591860 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)18661867 if handler is not None:1868 server_error = handler(server_error)18691870 return self.finalize_request(server_error, from_error_handler=True)18711872 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 the
581 unmodified lines
modified:tests/test_user_error_handler.py+95 added-2 removed
4 unmodified lines
56:copyright: © 2010 by the Pallets team.7:license: BSD, see LICENSE for more details.8"""9import pytest10from werkzeug.exceptions import Forbidden11from werkzeug.exceptions import HTTPException12from werkzeug.exceptions import InternalServerError13from werkzeug.exceptions import NotFound
11 unmodified lines
25 return "custom"2627 @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)3132 if original is not None:33 return "wrapped " + type(original).__name__3435 return "direct"3637 @app.route("/custom")38 def custom_test():39 raise CustomException()4041 @app.route("/keyerror")42 def key_error():43 raise KeyError()4445 @app.route("/abort")46 def do_abort():47 flask.abort(500)4849 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"535455def test_error_handler_subclass(app):56 class ParentException(Exception):
148 unmodified lines
205 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"209210211class TestGenericHandlers(object):212 """Test how very generic handlers are dispatched to."""213214 class Custom(Exception):215 pass216217 @pytest.fixture()218 def app(self, app):219 @app.route("/custom")220 def do_custom():221 raise self.Custom()222223 @app.route("/error")224 def do_error():225 raise KeyError()226227 @app.route("/abort")228 def do_abort():229 flask.abort(500)230231 @app.route("/raise")232 def do_raise():233 raise InternalServerError()234235 app.config["PROPAGATE_EXCEPTIONS"] = False236 return app237238 def report_error(self, e):239 original = getattr(e, "original_exception", None)240241 if original is not None:242 return "wrapped " + type(original).__name__243244 return "direct " + type(e).__name__245246 @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 """252253 @app.errorhandler(to_handle)254 def handle_500(e):255 assert isinstance(e, InternalServerError)256 return self.report_error(e)257258 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"262263 def test_handle_generic_http(self, app, client):264 """``HTTPException`` should only receive ``HTTPException``265 subclasses. It will receive ``404`` routing exceptions.266 """267268 @app.errorhandler(HTTPException)269 def handle_http(e):270 assert isinstance(e, HTTPException)271 return str(e.code)272273 assert client.get("/error").data == b"500"274 assert client.get("/abort").data == b"500"275 assert client.get("/not-found").data == b"404"276277 def test_handle_generic(self, app, client):278 """Generic ``Exception`` will handle all exceptions directly,279 including ``HTTPExceptions``.280 """281282 @app.errorhandler(Exception)283 def handle_exception(e):284 return self.report_error(e)285286 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 lines
10Unreleased1112- 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`2122 - :meth:`Flask.finalize_request` is called for all unhandled23 exceptions even if there is no ``500`` error handler.2425- :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 in
1011 unmodified lines