Skip to content
Myr

document behavior of very generic error handlers

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 9054f6d · Browse files · 3 files+89 added−5 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+89 added−5 removed

  • other:+89 added−5 removed

3 files+89 added−5 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+1 added-1 removed
1827 unmodified lines
1828 unhandled exception is available as ``e.original_exception``.18291830 .. note::1831 Prior to Werkzeug 1.0.0, ``InternalServerError`` will not1832 always have a ``original_exception`` attribute. Use1832 always have an ``original_exception`` attribute. Use1833 ``getattr(e, "original_exception", None)`` to simulate the1834 behavior for compatibility.18351836 .. versionchanged:: 1.1.0
620 unmodified lines
modified:CHANGES.rst+1 added-1 removed
14 unmodified lines
15 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 more19 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.
1016 unmodified lines