more changes to consolidated error handling docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Ebonne Cabarrus · committed by David Lord · parent 21c3df3 · Browse files · 2 files·+244 added−287 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+244 added−287 removed
- other:+244 added−287 removed
Provenance
- Commit
569c88d- Tree
07f1570- Author
Ebonne Cabarrus <42730922+ebonnecab@users.noreply.github.com>- Committer
David Lord <davidism@gmail.com>- Parent
21c3df3
2 files changed+244 added−287 removed
modified:docs/blueprints.rst+4 added-2 removed
240 unmodified lines241 242 This will link to ``admin.index`` for instance in case the current request243 was dispatched to any other admin blueprint endpoint.244 245-Error Handlers246---------------245+.. _my-blueprint-error-label:246 247+Blueprint Error Handlers248+------------------------249+250 Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`251 application object, so it is easy to make Blueprint-specific custom error252 pages.253 25 unmodified linesmodified:docs/errorhandling.rst+240 added-285 removed
24 unmodified lines25 26 But there is more you can do, and we will cover some better setups to deal27 with errors including custom exceptions and 3rd party tools.28 29-30-.. _common-error-codes:31-29 Common Error Codes33-``````````````````30+------------------31 32 The following error codes are some that are often displayed to the user,33 even if the application behaves correctly:34 27 unmodified lines62 Usually happens on programming errors or if the server is overloaded.63 A terribly good idea is to have a nice page there, because your64 application *will* fail sooner or later.65 66+Error Logging Tools67+-------------------68 69+Sending error mails, even if just for critical ones, can become70+overwhelming if enough users are hitting the error and log files are71+typically never looked at. This is why we recommend using `Sentry72+<https://sentry.io/>`_ for dealing with application errors. It's73+available as an Open Source project `on GitHub74+<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version75+<https://sentry.io/signup/>`_ which you can try for free. Sentry76+aggregates duplicate errors, captures the full stack trace and local77+variables for debugging, and sends you mails based on new errors or78+frequency thresholds.79 71-Default Error Handling72-``````````````````````80+To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::81 82+ $ pip install sentry-sdk[flask]83+84+And then add this to your Flask app::85+86+ import sentry_sdk87+ from sentry_sdk.integrations.flask import FlaskIntegration88+89+ sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])90+91+The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get92+from your Sentry installation.93+94+After installation, failures leading to an Internal Server Error95+are automatically reported to Sentry and from there you can96+receive error notifications.97+98+Follow-up reads:99+100+* Sentry also supports catching errors from your worker queue (RQ, Celery) in a101+ similar fashion. See the `Python SDK docs102+ <https://docs.sentry.io/platforms/python/>`_ for more information.103+* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_104+* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.105+106+.. _error-handlers:107+108+Error Handlers109+--------------110+111+You might want to show custom error pages to the user when an error occurs.112+This can be done by registering error handlers.113+114+An error handler is a function that returns a response when a type of error is115+raised, similar to how a view is a function that returns a response when a116+request URL is matched. It is passed the instance of the error being handled,117+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.118+119+The status code of the response will not be set to the handler's code. Make120+sure to provide the appropriate HTTP status code when returning a response from121+a handler.122+123+Registering124+```````````125+126+Register handlers by decorating a function with127+:meth:`~flask.Flask.errorhandler`. Or use128+:meth:`~flask.Flask.register_error_handler` to register the function later.129+Remember to set the error code when returning the response. ::130+131+ @app.errorhandler(werkzeug.exceptions.BadRequest)132+ def handle_bad_request(e):133+ return 'bad request!', 400134+135+ # or, without the decorator136+ app.register_error_handler(400, handle_bad_request)137+138+:exc:`werkzeug.exceptions.HTTPException` subclasses like139+:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable140+when registering handlers. (``BadRequest.code == 400``)141+142+Non-standard HTTP codes cannot be registered by code because they are not known143+by Werkzeug. Instead, define a subclass of144+:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and145+register and raise that exception class. ::146+147+ class InsufficientStorage(werkzeug.exceptions.HTTPException):148+ code = 507149+ description = 'Not enough storage space.'150+151+ app.register_error_handler(InsufficientStorage, handle_507)152+153+ raise InsufficientStorage()154+155+Handlers can be registered for any exception class, not just156+:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status157+codes. Handlers can be registered for a specific class, or for all subclasses158+of a parent class.159+160+Handling161+````````162+163 When building a Flask application you *will* run into exceptions. If some part164 of your code breaks while handling a request (and you have no error handlers76-registered) an "500 Internal Server Error"165+registered), a "500 Internal Server Error"166 (:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.78-Similarly, if a request is sent to an unregistered route a "404 Not Found"79-(:exc:`~werkzeug.exceptions.NotFound`) error will occur. If a route receives an80-unallowed request method a "405 Method Not Allowed"167+Similarly, "404 Not Found"168+(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.169+If a route receives an unallowed request method, a "405 Method Not Allowed"170 (:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all171 subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by172 default in Flask.173 174 Flask gives you to the ability to raise any HTTP exception registered by86-werkzeug. However, as the default HTTP exceptions return simple exception87-pages, Flask also offers the opportunity to customise these HTTP exceptions via88-custom error handlers as well as to add exception handlers for builtin and89-custom exceptions.175+Werkzeug. However, the default HTTP exceptions return simple exception176+pages. You might want to show custom error pages to the user when an error occurs.177+This can be done by registering error handlers.178 91-When an exception is caught by Flask while handling a request, it is first92-looked up by code. If no handler is registered for the code, it is looked up93-by its class hierarchy; the most specific handler is chosen. If no handler is94-registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a179+When Flask catches an exception while handling a request, it is first looked up by code.180+If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.181+If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a182 generic message about their code, while other exceptions are converted to a183 generic "500 Internal Server Error".184 185 For example, if an instance of :exc:`ConnectionRefusedError` is raised,6 unmodified lines192 raises the exception. However, the blueprint cannot handle 404 routing errors193 because the 404 occurs at the routing level before the blueprint can be194 determined.195 196+Generic Exception Handlers197+``````````````````````````198 199+It is possible to register error handlers for very generic base classes200+such as ``HTTPException`` or even ``Exception``. However, be aware that201+these will catch more than you might expect.202 111-.. _handling-errors:203+For example, an error handler for ``HTTPException`` might be useful for turning204+the default HTML errors pages into JSON. However, this205+handler will trigger for things you don't cause directly, such as 404206+and 405 errors during routing. Be sure to craft your handler carefully207+so you don't lose information about the HTTP error.208 113-Handling Errors114-```````````````115-116-Sometimes when building a Flask application, you might want to raise a117-:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that118-something is wrong with the request. Fortunately, Flask comes with a handy119-:func:`~flask.abort` function that aborts a request with a HTTP error from120-werkzeug as desired.121-122-Consider the code below, we might have a user profile route, but if the user123-fails to pass a username we raise a "400 Bad Request" and if the user passes a124-username but we can't find it, we raise a "404 Not Found".125-209 .. code-block:: python210 128- from flask import abort, render_template, request211+ from flask import json212+ from werkzeug.exceptions import HTTPException213 130- # a username needs to be supplied in the query args131- # a successful request would be like /profile?username=jack132- @app.route("/profile")133- def user_profile():134- username = request.arg.get("username")135- # if a username isn't supplied in the request, return a 400 bad request136- if username is None:137- abort(400)214+ @app.errorhandler(HTTPException)215+ def handle_exception(e):216+ """Return JSON instead of HTML for HTTP errors."""217+ # start with the correct headers and status code from the error218+ response = e.get_response()219+ # replace the body with JSON220+ response.data = json.dumps({221+ "code": e.code,222+ "name": e.name,223+ "description": e.description,224+ })225+ response.content_type = "application/json"226+ return response227 139- user = get_user(username=username)140- # if a user can't be found by their username, return 404 not found141- if user is None:142- abort(404)228 144- return render_template("profile.html", user=user)229+An error handler for ``Exception`` might seem useful for changing how230+all errors, even unhandled ones, are presented to the user. However,231+this is similar to doing ``except Exception:`` in Python, it will232+capture *all* otherwise unhandled errors, including all HTTP status233+codes.234 235+In most cases it will be safer to register handlers for more236+specific exceptions. Since ``HTTPException`` instances are valid WSGI237+responses, you could also pass them through directly.238 147-148-.. _custom-error-handlers:149-150-Custom error handlers151-`````````````````````152-153-The default :exc:`~werkzeug.exceptions.HTTPException` returns a black and white154-error page with a basic description, but nothing fancy. Considering155-these errors *will* be thrown during the lifetime of your application, it is156-highly advisable to customise these exceptions to improve the user experience157-of your site. This can be done by registering error handlers.158-159-An error handler is a normal view function that returns a response, but instead160-of being registered for a route, it is registered for an exception or HTTP161-status code that would be raised while trying to handle a request.162-163-It is passed the instance of the error being handled, which is most164-likely an integer that represents a :exc:`~werkzeug.exceptions.HTTPException`165-status code. For example 500 (an "Internal Server Error") which maps to166-:exc:`~werkzeug.exceptions.InternalServerError`.167-168-It is registered with the :meth:`~flask.Flask.errorhandler`169-decorator or the :meth:`~flask.Flask.register_error_handler` to register170-the function later. A handler can be registered for a status code,171-like 404 or 500, or for an built-in exception class, like KeyError,172-or a custom exception class that inherits from Exception or its subclasses.173-174-The status code of the response will not be set to the handler's code. Make175-sure to provide the appropriate HTTP status code when returning a response from176-a handler or a 200 OK HTTP code will be sent instead.177-239 .. code-block:: python240 180- from werkzeug.exceptions import InternalServerError241+ from werkzeug.exceptions import HTTPException242 182- # as a decorator with an int as the exception code183- @app.errorhandler(500)184- def handle_internal_server_error(e):185- # returning 500 with the text sets the error handler's code186- # make sure to provide the appropriate HTTP status code187- # otherwise 200 will be returned as default188- return 'Internal Server Error!', 500243+ @app.errorhandler(Exception)244+ def handle_exception(e):245+ # pass through HTTP errors246+ if isinstance(e, HTTPException):247+ return e248 190- # or, as a decorator with the werkzeug exception for internal server error191- @app.errorhandler(InternalServerError)192- def handle_internal_server_error(e):193- # werkzeug exceptions have a code attribute194- return 'Internal Server Error!', e.code249+ # now you're handling non-HTTP exceptions only250+ return render_template("500_generic.html", e=e), 500251 196- # or, without the decorator197- app.register_error_handler(500, handle_internal_server_error)252+Error handlers still respect the exception class hierarchy. If you253+register handlers for both ``HTTPException`` and ``Exception``, the254+``Exception`` handler will not handle ``HTTPException`` subclasses255+because it the ``HTTPException`` handler is more specific.256 199- # similarly with a werkzeug exception200- app.register_error_handler(InternalServerError, handle_internal_server_error)257+Unhandled Exceptions258+````````````````````259 260+When there is no error handler registered for an exception, a 500261+Internal Server Error will be returned instead. See262+:meth:`flask.Flask.handle_exception` for information about this263+behavior.264 203-204-A handler for "500 Internal Server Error" will not be used when running in205-debug mode. Instead, the interactive debugger will be shown.206-265 If there is an error handler registered for ``InternalServerError``,266 this will be invoked. As of Flask 1.1.0, this error handler will always267 be passed an instance of ``InternalServerError``, not the original268+unhandled error.269+210-unhandled error. The original error is available as ``e.original_exception``.270+The original error is available as ``e.original_exception``.271 Until Werkzeug 1.0.0, this attribute will only exist during unhandled272 errors, use ``getattr`` to get access it for compatibility.273 274 .. code-block:: python8 unmodified lines283 284 # wrapped unhandled error285 return render_template("500_unhandled.html", e=original), 500286 287+An error handler for "500 Internal Server Error" will be passed uncaught exceptions in288+addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.289+Instead, the interactive debugger will be shown.290 291+Custom Error Pages292+------------------293 229-Registering Custom Exceptions230------------------------------294+Sometimes when building a Flask application, you might want to raise a295+:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that296+something is wrong with the request. Fortunately, Flask comes with a handy297+:func:`~flask.abort` function that aborts a request with a HTTP error from298+werkzeug as desired. It will also provide a plain black and white error page299+for you with a basic description, but nothing fancy.300 232-You can create your own custom exceptions by subclassing233-:exc:`werkzeug.exceptions.HTTPException`. As shown above, integer HTTP codes234-are interchangable when registering handlers. (``BadRequest.code == 400``)301+Depending on the error code it is less or more likely for the user to302+actually see such an error.303 236-Non-standard HTTP codes cannot be registered by code because they are not known237-by Werkzeug. Instead, define a subclass of238-:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and239-register and raise that exception class:304+Consider the code below, we might have a user profile route, and if the user305+fails to pass a username we can raise a "400 Bad Request". If the user passes a306+username and we can't find it, we raise a "404 Not Found".307 308 .. code-block:: python309 243- class InsufficientStorage(werkzeug.exceptions.HTTPException):244- code = 507245- description = 'Not enough storage space.'310+ from flask import abort, render_template, request311 247- def handle_507(e):248- return 'Not enough storage space!', 507312+ # a username needs to be supplied in the query args313+ # a successful request would be like /profile?username=jack314+ @app.route("/profile")315+ def user_profile():316+ username = request.arg.get("username")317+ # if a username isn't supplied in the request, return a 400 bad request318+ if username is None:319+ abort(400)320 250- app.register_error_handler(InsufficientStorage, handle_507)321+ user = get_user(username=username)322+ # if a user can't be found by their username, return 404 not found323+ if user is None:324+ abort(404)325 252- # during an request253- raise InsufficientStorage()326+ return render_template("profile.html", user=user)327 255-Handlers can be registered for any exception class that inherits from Exception.328+Here is another example implementation for a "404 Page Not Found" exception::329 330+ from flask import render_template331 258-Unhandled Exceptions259---------------------332+ @app.errorhandler(404)333+ def page_not_found(e):334+ # note that we set the 404 status explicitly335+ return render_template('404.html'), 404336 261-If an exception is raised in the code while Flask is handling a request and262-there is no error handler registered for that exception, a "500 Internal Server263-Error" will be returned instead. See :meth:`flask.Flask.handle_exception` for264-information about this behavior.337+When using :doc:`/patterns/appfactories`::338 266-Custom error pages267-------------------339+ from flask import Flask, render_template340 341+ def page_not_found(e):342+ return render_template('404.html'), 404343+344+ def create_app(config_filename):345+ app = Flask(__name__)346+ app.register_error_handler(404, page_not_found)347+ return app348+349+An example template might be this:350+351+.. sourcecode:: html+jinja352+353+ {% extends "layout.html" %}354+ {% block title %}Page Not Found{% endblock %}355+ {% block body %}356+ <h1>Page Not Found</h1>357+ <p>What you were looking for is just not there.358+ <p><a href="{{ url_for('index') }}">go somewhere nice</a>359+ {% endblock %}360+361+Further Examples362+````````````````363+364 The above examples wouldn't actually be an improvement on the default365 exception pages. We can create a custom 500.html template like this:366 367 .. sourcecode:: html+jinja17 unmodified lines385 # note that we set the 500 status explicitly386 return render_template('500.html'), 500387 388 294-When using the :doc:`/patterns/appfactories`:389+When using :doc:`/patterns/appfactories`:390 391 .. code-block:: python392 393 23 unmodified lines417 418 # or with register_error_handler419 blog.register_error_handler(500, internal_server_error)420 421+Blueprint Error Handling422+````````````````````````423 327-328-In blueprints errorhandlers will simply work as expected; however, there is a caveat329-concerning handlers for 404 and 405 exceptions. These errorhandlers are only424+In blueprints, error handlers will work as expected. However, there is a caveat425+concerning handlers for 404 and 405 exceptions. These error handlers are only426 invoked from an appropriate ``raise`` statement or a call to ``abort`` in another427 of the blueprint's view functions; they are not invoked by, e.g., an invalid URL428+access.429+332-access. This is because the blueprint does not "own" a certain URL space, so430+This is because the blueprint does not "own" a certain URL space, so431 the application instance has no way of knowing which blueprint error handler it334-should run if given an invalid URL. If you would like to execute different432+should run if given an invalid URL. If you would like to execute different433 handling strategies for these errors based on URL prefixes, they may be defined434 at the application level using the ``request`` proxy object:435 436 .. code-block:: python24 unmodified lines461 return render_template("405.html"), 405462 463 464 367-More information on error handling with blueprint can be found in368-:doc:`/blueprints`.465+For more information on Blueprint Error Handling see :ref:`my-blueprint-error-label`.466 370-467 Returning API errors as JSON468 ````````````````````````````469 374-When building APIs in Flask, some developers realise that the builtin470+When building APIs in Flask, some developers realise that the built-in471 exceptions are not expressive enough for APIs and that the content type of472 :mimetype:`text/html` they are emitting is not very useful for API consumers.473 474 Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON475 responses to API errors. :func:`~flask.abort` is called380-with a ``description`` parameter. The errorhandler will476+with a ``description`` parameter. The error handler will477 use that as the JSON error message, and set the status code to 404.478 479 .. code-block:: python480 11 unmodified lines492 abort(404, description="Resource not found")493 494 return jsonify(resource)495 400-401-402-We can also create custom exception classes; for instance, for an API we can403-introduce a new custom exception that can take a proper human readable message,496+We can also create custom exception classes. For instance, we can497+introduce a new custom exception for an API that can take a proper human readable message,498 a status code for the error and some optional payload to give more context499 for the error.500 501 This is a simple example:35 unmodified lines537 538 return jsonify(user.to_dict())539 540 447-A view can now raise that exception with an error message. Additionally541+A view can now raise that exception with an error message. Additionally542 some extra payload can be provided as a dictionary through the `payload`543 parameter.544 545+Logging546+-------547 452-Generic Exception Handlers453-``````````````````````````548+See :doc:`/logging` for information on how to log exceptions, such as by549+emailing them to admins.550 455-It is possible to register error handlers for very generic base classes456-such as ``HTTPException`` or even ``Exception``. However, be aware that457-these will catch more than you might expect.458-459-An error handler for ``HTTPException`` might be useful for turning460-the default HTML errors pages into JSON, for example. However, this461-handler will trigger for things you don't cause directly, such as 404462-and 405 errors during routing. Be sure to craft your handler carefully463-so you don't lose information about the HTTP error.464-465-.. code-block:: python466-467- from flask import json468- from werkzeug.exceptions import HTTPException469-470- @app.errorhandler(HTTPException)471- def handle_exception(e):472- """Return JSON instead of HTML for HTTP errors."""473- # start with the correct headers and status code from the error474- response = e.get_response()475- # replace the body with JSON476- response.data = json.dumps({477- "code": e.code,478- "name": e.name,479- "description": e.description,480- })481- response.content_type = "application/json"482- return response483-484- # or using jsonify485- @app.errorhandler(HTTPException)486- def handle_exception(e):487- return jsonify("code": e.code, "name": e.name, "description": e.description), e.code488-489-490-An error handler for ``Exception`` might seem useful for changing how491-all errors, even unhandled ones, are presented to the user. However,492-this is similar to doing ``except Exception:`` in Python, it will493-capture *all* otherwise unhandled errors, including all HTTP status494-codes. In most cases it will be safer to register handlers for more495-specific exceptions. Since ``HTTPException`` instances are valid WSGI496-responses, you could also pass them through directly.497-498-.. code-block:: python499-500- from werkzeug.exceptions import HTTPException501-502- @app.errorhandler(Exception)503- def handle_exception(e):504- # pass through HTTP errors505- if isinstance(e, HTTPException):506- return e507-508- # now you're handling non-HTTP exceptions only509- return render_template("500_generic.html", e=e), 500510-511-Error handlers still respect the exception class hierarchy. If you512-register handlers for both ``HTTPException`` and ``Exception``, the513-``Exception`` handler will not handle ``HTTPException`` subclasses514-because it the ``HTTPException`` handler is more specific.515-516-517-Generic Error Pages518--------------------519-520-If we pass in the exception into a template as below:521-522-.. code-block:: python523-524- from werkzeug.exceptions import HTTPException525-526- @app.errorhandler(HTTPException)527- def handle_exception(e):528- return render_template("exception.html", e=e), e.code529-530-531-532-.. sourcecode:: html+jinja533-534- {% extends "layout.html" %}535- {% block title %}{{ e.name }}{% endblock %}536- {% block body %}537- <h1>{{ e.code }} {{ e.name }}</h1>538- <p>{{ e.description }}</p>539- <p><a href="{{ url_for('index') }}">Go home</a>540- {% endblock %}541-542-543-551 Debugging Application Errors545-````````````````````````````552+============================553 554 For production applications, configure your application with logging and555 notifications as described in :doc:`/logging`. This section provides556 pointers when debugging deployment configuration and digging deeper with a557 full-featured Python debugger.558 552-Logging553--------554-555-See :doc:`/logging` for information on how to log exceptions, such as by556-emailing them to admins.557-558-559-559 When in Doubt, Run Manually560 ---------------------------561 562 Having problems getting your application configured for production? If you43 unmodified lines606 607 use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))608 app.run(use_debugger=use_debugger, debug=app.debug,609 use_reloader=use_debugger, host='0.0.0.0')611-612-613-.. _error-logging-tools:614-615-616-Error Logging Tools617--------------------618-619-Sending error mails, even if just for critical ones, can become620-overwhelming if enough users are hitting the error and log files are621-typically never looked at. This is why we recommend using `Sentry622-<https://sentry.io/>`_ for dealing with application errors. It's623-available as an Open Source project `on GitHub624-<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version625-<https://sentry.io/signup/>`_ which you can try for free. Sentry626-aggregates duplicate errors, captures the full stack trace and local627-variables for debugging, and sends you mails based on new errors or628-frequency thresholds.629-630-To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::631-632- $ pip install sentry-sdk[flask]633-634-And then add this to your Flask app::635-636- import sentry_sdk637- from sentry_sdk.integrations.flask import FlaskIntegration638-639- sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])640-641-The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get642-from your Sentry installation.643-644-After installation, failures leading to an Internal Server Error645-are automatically reported to Sentry and from there you can646-receive error notifications.647-648-Follow-up reads:649-650-* Sentry also supports catching errors from your worker queue (RQ, Celery) in a651- similar fashion. See the `Python SDK docs652- <https://docs.sentry.io/platforms/python/>`_ for more information.653-* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_654-* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.