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
Provenance
- Commit
54519ef- Tree
cb72e65- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9054f6d
3 files changed+89 added−5 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+1 added-1 removed
1827 unmodified lines1828 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. Use1832+ always have an ``original_exception`` attribute. Use1833 ``getattr(e, "original_exception", None)`` to simulate the1834 behavior for compatibility.1835 1836 .. versionchanged:: 1.1.0620 unmodified linesmodified:CHANGES.rst+1 added-1 removed
14 unmodified lines15 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`21 22 - :meth:`Flask.finalize_request` is called for all unhandled23 exceptions even if there is no ``500`` error handler.1016 unmodified lines