Skip to content
Myr

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

2 files+244 added−287 removed

modified:docs/blueprints.rst+4 added-2 removed
240 unmodified lines
241242This will link to ``admin.index`` for instance in case the current request243was dispatched to any other admin blueprint endpoint.244245Error Handlers246--------------245.. _my-blueprint-error-label:246247Blueprint Error Handlers248------------------------249250Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`251application object, so it is easy to make Blueprint-specific custom error252pages.253
25 unmodified lines
modified:docs/errorhandling.rst+240 added-285 removed
24 unmodified lines
2526But there is more you can do, and we will cover some better setups to deal27with errors including custom exceptions and 3rd party tools.282930.. _common-error-codes:3129Common Error Codes33``````````````````30------------------3132The following error codes are some that are often displayed to the user,33even if the application behaves correctly:34
27 unmodified lines
62 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.6566Error Logging Tools67-------------------6869Sending error mails, even if just for critical ones, can become70overwhelming if enough users are hitting the error and log files are71typically never looked at. This is why we recommend using `Sentry72<https://sentry.io/>`_ for dealing with application errors. It's73available 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. Sentry76aggregates duplicate errors, captures the full stack trace and local77variables for debugging, and sends you mails based on new errors or78frequency thresholds.7971Default Error Handling72``````````````````````80To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::8182 $ pip install sentry-sdk[flask]8384And then add this to your Flask app::8586 import sentry_sdk87 from sentry_sdk.integrations.flask import FlaskIntegration8889 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])9091The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get92from your Sentry installation.9394After installation, failures leading to an Internal Server Error95are automatically reported to Sentry and from there you can96receive error notifications.9798Follow-up reads:99100* 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/>`_.105106.. _error-handlers:107108Error Handlers109--------------110111You might want to show custom error pages to the user when an error occurs.112This can be done by registering error handlers.113114An error handler is a function that returns a response when a type of error is115raised, similar to how a view is a function that returns a response when a116request URL is matched. It is passed the instance of the error being handled,117which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.118119The status code of the response will not be set to the handler's code. Make120sure to provide the appropriate HTTP status code when returning a response from121a handler.122123Registering124```````````125126Register handlers by decorating a function with127:meth:`~flask.Flask.errorhandler`. Or use128:meth:`~flask.Flask.register_error_handler` to register the function later.129Remember to set the error code when returning the response. ::130131 @app.errorhandler(werkzeug.exceptions.BadRequest)132 def handle_bad_request(e):133 return 'bad request!', 400134135 # or, without the decorator136 app.register_error_handler(400, handle_bad_request)137138:exc:`werkzeug.exceptions.HTTPException` subclasses like139:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable140when registering handlers. (``BadRequest.code == 400``)141142Non-standard HTTP codes cannot be registered by code because they are not known143by Werkzeug. Instead, define a subclass of144:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and145register and raise that exception class. ::146147 class InsufficientStorage(werkzeug.exceptions.HTTPException):148 code = 507149 description = 'Not enough storage space.'150151 app.register_error_handler(InsufficientStorage, handle_507)152153 raise InsufficientStorage()154155Handlers can be registered for any exception class, not just156:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status157codes. Handlers can be registered for a specific class, or for all subclasses158of a parent class.159160Handling161````````162163When building a Flask application you *will* run into exceptions. If some part164of your code breaks while handling a request (and you have no error handlers76registered) an "500 Internal Server Error"165registered), a "500 Internal Server Error"166(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.78Similarly, 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 an80unallowed request method a "405 Method Not Allowed"167Similarly, "404 Not Found"168(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.169If a route receives an unallowed request method, a "405 Method Not Allowed"170(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all171subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by172default in Flask.173174Flask gives you to the ability to raise any HTTP exception registered by86werkzeug. However, as the default HTTP exceptions return simple exception87pages, Flask also offers the opportunity to customise these HTTP exceptions via88custom error handlers as well as to add exception handlers for builtin and89custom exceptions.175Werkzeug. However, the default HTTP exceptions return simple exception176pages. You might want to show custom error pages to the user when an error occurs.177This can be done by registering error handlers.17891When an exception is caught by Flask while handling a request, it is first92looked up by code. If no handler is registered for the code, it is looked up93by its class hierarchy; the most specific handler is chosen. If no handler is94registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a179When Flask catches an exception while handling a request, it is first looked up by code.180If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.181If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a182generic message about their code, while other exceptions are converted to a183generic "500 Internal Server Error".184185For example, if an instance of :exc:`ConnectionRefusedError` is raised,
6 unmodified lines
192raises the exception. However, the blueprint cannot handle 404 routing errors193because the 404 occurs at the routing level before the blueprint can be194determined.195196Generic Exception Handlers197``````````````````````````198199It is possible to register error handlers for very generic base classes200such as ``HTTPException`` or even ``Exception``. However, be aware that201these will catch more than you might expect.202111.. _handling-errors:203For example, an error handler for ``HTTPException`` might be useful for turning204the default HTML errors pages into JSON. However, this205handler will trigger for things you don't cause directly, such as 404206and 405 errors during routing. Be sure to craft your handler carefully207so you don't lose information about the HTTP error.208113Handling Errors114```````````````115116Sometimes when building a Flask application, you might want to raise a117:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that118something is wrong with the request. Fortunately, Flask comes with a handy119:func:`~flask.abort` function that aborts a request with a HTTP error from120werkzeug as desired.121122Consider the code below, we might have a user profile route, but if the user123fails to pass a username we raise a "400 Bad Request" and if the user passes a124username but we can't find it, we raise a "404 Not Found".125209.. code-block:: python210128 from flask import abort, render_template, request211 from flask import json212 from werkzeug.exceptions import HTTPException213130 # 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 response227139 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)228144 return render_template("profile.html", user=user)229An error handler for ``Exception`` might seem useful for changing how230all errors, even unhandled ones, are presented to the user. However,231this is similar to doing ``except Exception:`` in Python, it will232capture *all* otherwise unhandled errors, including all HTTP status233codes.234235In most cases it will be safer to register handlers for more236specific exceptions. Since ``HTTPException`` instances are valid WSGI237responses, you could also pass them through directly.238147148.. _custom-error-handlers:149150Custom error handlers151`````````````````````152153The default :exc:`~werkzeug.exceptions.HTTPException` returns a black and white154error page with a basic description, but nothing fancy. Considering155these errors *will* be thrown during the lifetime of your application, it is156highly advisable to customise these exceptions to improve the user experience157of your site. This can be done by registering error handlers.158159An error handler is a normal view function that returns a response, but instead160of being registered for a route, it is registered for an exception or HTTP161status code that would be raised while trying to handle a request.162163It is passed the instance of the error being handled, which is most164likely an integer that represents a :exc:`~werkzeug.exceptions.HTTPException`165status code. For example 500 (an "Internal Server Error") which maps to166:exc:`~werkzeug.exceptions.InternalServerError`.167168It is registered with the :meth:`~flask.Flask.errorhandler`169decorator or the :meth:`~flask.Flask.register_error_handler` to register170the function later. A handler can be registered for a status code,171like 404 or 500, or for an built-in exception class, like KeyError,172or a custom exception class that inherits from Exception or its subclasses.173174The status code of the response will not be set to the handler's code. Make175sure to provide the appropriate HTTP status code when returning a response from176a handler or a 200 OK HTTP code will be sent instead.177239.. code-block:: python240180 from werkzeug.exceptions import InternalServerError241 from werkzeug.exceptions import HTTPException242182 # 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 e248190 # 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), 500251196 # or, without the decorator197 app.register_error_handler(500, handle_internal_server_error)252Error handlers still respect the exception class hierarchy. If you253register handlers for both ``HTTPException`` and ``Exception``, the254``Exception`` handler will not handle ``HTTPException`` subclasses255because it the ``HTTPException`` handler is more specific.256199 # similarly with a werkzeug exception200 app.register_error_handler(InternalServerError, handle_internal_server_error)257Unhandled Exceptions258````````````````````259260When there is no error handler registered for an exception, a 500261Internal Server Error will be returned instead. See262:meth:`flask.Flask.handle_exception` for information about this263behavior.264203204A handler for "500 Internal Server Error" will not be used when running in205debug mode. Instead, the interactive debugger will be shown.206265If there is an error handler registered for ``InternalServerError``,266this will be invoked. As of Flask 1.1.0, this error handler will always267be passed an instance of ``InternalServerError``, not the original268unhandled error.269210unhandled error. The original error is available as ``e.original_exception``.270The original error is available as ``e.original_exception``.271Until Werkzeug 1.0.0, this attribute will only exist during unhandled272errors, use ``getattr`` to get access it for compatibility.273274.. code-block:: python
8 unmodified lines
283284 # wrapped unhandled error285 return render_template("500_unhandled.html", e=original), 500286287An error handler for "500 Internal Server Error" will be passed uncaught exceptions in288addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.289Instead, the interactive debugger will be shown.290291Custom Error Pages292------------------293229Registering Custom Exceptions230-----------------------------294Sometimes when building a Flask application, you might want to raise a295:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that296something is wrong with the request. Fortunately, Flask comes with a handy297:func:`~flask.abort` function that aborts a request with a HTTP error from298werkzeug as desired. It will also provide a plain black and white error page299for you with a basic description, but nothing fancy.300232You can create your own custom exceptions by subclassing233:exc:`werkzeug.exceptions.HTTPException`. As shown above, integer HTTP codes234are interchangable when registering handlers. (``BadRequest.code == 400``)301Depending on the error code it is less or more likely for the user to302actually see such an error.303236Non-standard HTTP codes cannot be registered by code because they are not known237by Werkzeug. Instead, define a subclass of238:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and239register and raise that exception class:304Consider the code below, we might have a user profile route, and if the user305fails to pass a username we can raise a "400 Bad Request". If the user passes a306username and we can't find it, we raise a "404 Not Found".307308.. code-block:: python309243 class InsufficientStorage(werkzeug.exceptions.HTTPException):244 code = 507245 description = 'Not enough storage space.'310 from flask import abort, render_template, request311247 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)320250 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)325252 # during an request253 raise InsufficientStorage()326 return render_template("profile.html", user=user)327255Handlers can be registered for any exception class that inherits from Exception.328Here is another example implementation for a "404 Page Not Found" exception::329330 from flask import render_template331258Unhandled 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'), 404336261If an exception is raised in the code while Flask is handling a request and262there is no error handler registered for that exception, a "500 Internal Server263Error" will be returned instead. See :meth:`flask.Flask.handle_exception` for264information about this behavior.337When using :doc:`/patterns/appfactories`::338266Custom error pages267------------------339 from flask import Flask, render_template340341 def page_not_found(e):342 return render_template('404.html'), 404343344 def create_app(config_filename):345 app = Flask(__name__)346 app.register_error_handler(404, page_not_found)347 return app348349An example template might be this:350351.. sourcecode:: html+jinja352353 {% 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 %}360361Further Examples362````````````````363364The above examples wouldn't actually be an improvement on the default365exception pages. We can create a custom 500.html template like this:366367.. sourcecode:: html+jinja
17 unmodified lines
385 # note that we set the 500 status explicitly386 return render_template('500.html'), 500387388294When using the :doc:`/patterns/appfactories`:389When using :doc:`/patterns/appfactories`:390391.. code-block:: python392393
23 unmodified lines
417418 # or with register_error_handler419 blog.register_error_handler(500, internal_server_error)420421Blueprint Error Handling422````````````````````````423327328In blueprints errorhandlers will simply work as expected; however, there is a caveat329concerning handlers for 404 and 405 exceptions. These errorhandlers are only424In blueprints, error handlers will work as expected. However, there is a caveat425concerning handlers for 404 and 405 exceptions. These error handlers are only426invoked from an appropriate ``raise`` statement or a call to ``abort`` in another427of the blueprint's view functions; they are not invoked by, e.g., an invalid URL428access.429332access. This is because the blueprint does not "own" a certain URL space, so430This is because the blueprint does not "own" a certain URL space, so431the application instance has no way of knowing which blueprint error handler it334should run if given an invalid URL. If you would like to execute different432should run if given an invalid URL. If you would like to execute different433handling strategies for these errors based on URL prefixes, they may be defined434at the application level using the ``request`` proxy object:435436.. code-block:: python
24 unmodified lines
461 return render_template("405.html"), 405462463464367More information on error handling with blueprint can be found in368:doc:`/blueprints`.465For more information on Blueprint Error Handling see :ref:`my-blueprint-error-label`.466370467Returning API errors as JSON468````````````````````````````469374When building APIs in Flask, some developers realise that the builtin470When building APIs in Flask, some developers realise that the built-in471exceptions 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.473474Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON475responses to API errors. :func:`~flask.abort` is called380with a ``description`` parameter. The errorhandler will476with a ``description`` parameter. The error handler will477use that as the JSON error message, and set the status code to 404.478479.. code-block:: python480
11 unmodified lines
492 abort(404, description="Resource not found")493494 return jsonify(resource)495400401402We can also create custom exception classes; for instance, for an API we can403introduce a new custom exception that can take a proper human readable message,496We can also create custom exception classes. For instance, we can497introduce a new custom exception for an API that can take a proper human readable message,498a status code for the error and some optional payload to give more context499for the error.500501This is a simple example:
35 unmodified lines
537538 return jsonify(user.to_dict())539540447A view can now raise that exception with an error message. Additionally541A view can now raise that exception with an error message. Additionally542some extra payload can be provided as a dictionary through the `payload`543parameter.544545Logging546-------547452Generic Exception Handlers453``````````````````````````548See :doc:`/logging` for information on how to log exceptions, such as by549emailing them to admins.550455It is possible to register error handlers for very generic base classes456such as ``HTTPException`` or even ``Exception``. However, be aware that457these will catch more than you might expect.458459An error handler for ``HTTPException`` might be useful for turning460the default HTML errors pages into JSON, for example. However, this461handler will trigger for things you don't cause directly, such as 404462and 405 errors during routing. Be sure to craft your handler carefully463so you don't lose information about the HTTP error.464465.. code-block:: python466467 from flask import json468 from werkzeug.exceptions import HTTPException469470 @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 response483484 # or using jsonify485 @app.errorhandler(HTTPException)486 def handle_exception(e):487 return jsonify("code": e.code, "name": e.name, "description": e.description), e.code488489490An error handler for ``Exception`` might seem useful for changing how491all errors, even unhandled ones, are presented to the user. However,492this is similar to doing ``except Exception:`` in Python, it will493capture *all* otherwise unhandled errors, including all HTTP status494codes. In most cases it will be safer to register handlers for more495specific exceptions. Since ``HTTPException`` instances are valid WSGI496responses, you could also pass them through directly.497498.. code-block:: python499500 from werkzeug.exceptions import HTTPException501502 @app.errorhandler(Exception)503 def handle_exception(e):504 # pass through HTTP errors505 if isinstance(e, HTTPException):506 return e507508 # now you're handling non-HTTP exceptions only509 return render_template("500_generic.html", e=e), 500510511Error handlers still respect the exception class hierarchy. If you512register handlers for both ``HTTPException`` and ``Exception``, the513``Exception`` handler will not handle ``HTTPException`` subclasses514because it the ``HTTPException`` handler is more specific.515516517Generic Error Pages518-------------------519520If we pass in the exception into a template as below:521522.. code-block:: python523524 from werkzeug.exceptions import HTTPException525526 @app.errorhandler(HTTPException)527 def handle_exception(e):528 return render_template("exception.html", e=e), e.code529530531532.. sourcecode:: html+jinja533534 {% 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 %}541542543551Debugging Application Errors545````````````````````````````552============================553554For production applications, configure your application with logging and555notifications as described in :doc:`/logging`. This section provides556pointers when debugging deployment configuration and digging deeper with a557full-featured Python debugger.558552Logging553-------554555See :doc:`/logging` for information on how to log exceptions, such as by556emailing them to admins.557558559559When in Doubt, Run Manually560---------------------------561562Having problems getting your application configured for production? If you
43 unmodified lines
606607 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')611612613.. _error-logging-tools:614615616Error Logging Tools617-------------------618619Sending error mails, even if just for critical ones, can become620overwhelming if enough users are hitting the error and log files are621typically never looked at. This is why we recommend using `Sentry622<https://sentry.io/>`_ for dealing with application errors. It's623available 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. Sentry626aggregates duplicate errors, captures the full stack trace and local627variables for debugging, and sends you mails based on new errors or628frequency thresholds.629630To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::631632 $ pip install sentry-sdk[flask]633634And then add this to your Flask app::635636 import sentry_sdk637 from sentry_sdk.integrations.flask import FlaskIntegration638639 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])640641The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get642from your Sentry installation.643644After installation, failures leading to an Internal Server Error645are automatically reported to Sentry and from there you can646receive error notifications.647648Follow-up reads:649650* 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/>`_.