Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

297 lines · 11.1 KiB

Last changed by

Merge pull request #3282 from pallets/logger-nameDavid Lordbefore adoption6665c91

History of this file

Take it

1.. _application-errors:23Application Errors4==================56.. versionadded:: 0.378Applications fail, servers fail.  Sooner or later you will see an exception9in production.  Even if your code is 100% correct, you will still see10exceptions from time to time.  Why?  Because everything else involved will11fail.  Here are some situations where perfectly fine code can lead to server12errors:1314-   the client terminated the request early and the application was still15    reading from the incoming data16-   the database server was overloaded and could not handle the query17-   a filesystem is full18-   a harddrive crashed19-   a backend server overloaded20-   a programming error in a library you are using21-   network connection of the server to another system failed2223And that's just a small sample of issues you could be facing.  So how do we24deal with that sort of problem?  By default if your application runs in25production mode, Flask will display a very simple page for you and log the26exception to the :attr:`~flask.Flask.logger`.2728But there is more you can do, and we will cover some better setups to deal29with errors.3031Error Logging Tools32-------------------3334Sending error mails, even if just for critical ones, can become35overwhelming if enough users are hitting the error and log files are36typically never looked at. This is why we recommend using `Sentry37<https://sentry.io/>`_ for dealing with application errors.  It's38available as an Open Source project `on GitHub39<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version40<https://sentry.io/signup/>`_ which you can try for free. Sentry41aggregates duplicate errors, captures the full stack trace and local42variables for debugging, and sends you mails based on new errors or43frequency thresholds.4445To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::4647    $ pip install sentry-sdk[flask]4849And then add this to your Flask app::5051    import sentry_sdk52    from sentry_sdk.integrations.flask import FlaskIntegration5354    sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])5556The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get57from your Sentry installation.5859After installation, failures leading to an Internal Server Error60are automatically reported to Sentry and from there you can61receive error notifications.6263Follow-up reads:6465* Sentry also supports catching errors from your worker queue (RQ, Celery) in a66  similar fashion.  See the `Python SDK docs67  <https://docs.sentry.io/platforms/python/>`_ for more information.68* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_69* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.7071.. _error-handlers:7273Error handlers74--------------7576You might want to show custom error pages to the user when an error occurs.77This can be done by registering error handlers.7879An error handler is a normal view function that returns a response, but instead80of being registered for a route, it is registered for an exception or HTTP81status code that would be raised while trying to handle a request.8283Registering84```````````8586Register handlers by decorating a function with87:meth:`~flask.Flask.errorhandler`. Or use88:meth:`~flask.Flask.register_error_handler` to register the function later.89Remember to set the error code when returning the response. ::9091    @app.errorhandler(werkzeug.exceptions.BadRequest)92    def handle_bad_request(e):93        return 'bad request!', 4009495    # or, without the decorator96    app.register_error_handler(400, handle_bad_request)9798:exc:`werkzeug.exceptions.HTTPException` subclasses like99:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable100when registering handlers. (``BadRequest.code == 400``)101102Non-standard HTTP codes cannot be registered by code because they are not known103by Werkzeug. Instead, define a subclass of104:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105register and raise that exception class. ::106107    class InsufficientStorage(werkzeug.exceptions.HTTPException):108        code = 507109        description = 'Not enough storage space.'110111    app.register_error_handler(InsufficientStorage, handle_507)112113    raise InsufficientStorage()114115Handlers can be registered for any exception class, not just116:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status117codes. Handlers can be registered for a specific class, or for all subclasses118of a parent class.119120Handling121````````122123When an exception is caught by Flask while handling a request, it is first124looked up by code. If no handler is registered for the code, it is looked up125by its class hierarchy; the most specific handler is chosen. If no handler is126registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a127generic message about their code, while other exceptions are converted to a128generic 500 Internal Server Error.129130For example, if an instance of :exc:`ConnectionRefusedError` is raised,131and a handler is registered for :exc:`ConnectionError` and132:exc:`ConnectionRefusedError`,133the more specific :exc:`ConnectionRefusedError` handler is called with the134exception instance to generate the response.135136Handlers registered on the blueprint take precedence over those registered137globally on the application, assuming a blueprint is handling the request that138raises the exception. However, the blueprint cannot handle 404 routing errors139because the 404 occurs at the routing level before the blueprint can be140determined.141142143Generic 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 :doc:`/logging` for information on how to log exceptions, such as by235emailing them to admins.236237238Debugging Application Errors239============================240241For production applications, configure your application with logging and242notifications as described in :ref:`application-errors`.  This section provides243pointers when debugging deployment configuration and digging deeper with a244full-featured Python debugger.245246247When in Doubt, Run Manually248---------------------------249250Having problems getting your application configured for production?  If you251have shell access to your host, verify that you can run your application252manually from the shell in the deployment environment.  Be sure to run under253the same user account as the configured deployment to troubleshoot permission254issues.  You can use Flask's builtin development server with `debug=True` on255your production host, which is helpful in catching configuration issues, but256**be sure to do this temporarily in a controlled environment.** Do not run in257production with `debug=True`.258259260.. _working-with-debuggers:261262Working with Debuggers263----------------------264265To dig deeper, possibly to trace code execution, Flask provides a debugger out266of the box (see :ref:`debug-mode`).  If you would like to use another Python267debugger, note that debuggers interfere with each other.  You have to set some268options in order to use your favorite debugger:269270* ``debug``        - whether to enable debug mode and catch exceptions271* ``use_debugger`` - whether to use the internal Flask debugger272* ``use_reloader`` - whether to reload and fork the process if modules273  were changed274275``debug`` must be True (i.e., exceptions must be caught) in order for the other276two options to have any value.277278If you're using Aptana/Eclipse for debugging you'll need to set both279``use_debugger`` and ``use_reloader`` to False.280281A possible useful pattern for configuration is to set the following in your282config.yaml (change the block as appropriate for your application, of course)::283284   FLASK:285       DEBUG: True286       DEBUG_WITH_APTANA: True287288Then in your application's entry-point (main.py),289you could have something like::290291   if __name__ == "__main__":292       # To allow aptana to receive errors, set use_debugger=False293       app = create_app(config="config.yaml")294295       use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))296       app.run(use_debugger=use_debugger, debug=app.debug,297               use_reloader=use_debugger, host='0.0.0.0')