Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

215 lines · 7.9 KiB

Last changed by

Merge pull request #3270 from pallets/metadataDavid Lordbefore adoption31d3c7e

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/welcome/>`_ 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 `raven` client with extra `flask` dependencies::4647    $ pip install raven[flask]4849And then add this to your Flask app::5051    from raven.contrib.flask import Sentry52    sentry = Sentry(app, dsn='YOUR_DSN_HERE')5354Or if you are using factories you can also init it later::5556    from raven.contrib.flask import Sentry57    sentry = Sentry(dsn='YOUR_DSN_HERE')5859    def create_app():60        app = Flask(__name__)61        sentry.init_app(app)62        ...63        return app6465The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get66from your Sentry installation.6768Afterwards failures are automatically reported to Sentry and from there69you can receive error notifications.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 return a response, but instead80of being registered for a route, it is registered for an exception or HTTP81status code that would is 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(InsuffcientStorage, 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, and a handler131is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,132the more specific :exc:`ConnectionRefusedError` handler is called with the133exception instance to generate the response.134135Handlers registered on the blueprint take precedence over those registered136globally on the application, assuming a blueprint is handling the request that137raises the exception. However, the blueprint cannot handle 404 routing errors138because the 404 occurs at the routing level before the blueprint can be139determined.140141.. versionchanged:: 0.11142143   Handlers are prioritized by specificity of the exception classes they are144   registered for instead of the order they are registered in.145146Logging147-------148149See :ref:`logging` for information on how to log exceptions, such as by150emailing them to admins.151152153Debugging Application Errors154============================155156For production applications, configure your application with logging and157notifications as described in :ref:`application-errors`.  This section provides158pointers when debugging deployment configuration and digging deeper with a159full-featured Python debugger.160161162When in Doubt, Run Manually163---------------------------164165Having problems getting your application configured for production?  If you166have shell access to your host, verify that you can run your application167manually from the shell in the deployment environment.  Be sure to run under168the same user account as the configured deployment to troubleshoot permission169issues.  You can use Flask's builtin development server with `debug=True` on170your production host, which is helpful in catching configuration issues, but171**be sure to do this temporarily in a controlled environment.** Do not run in172production with `debug=True`.173174175.. _working-with-debuggers:176177Working with Debuggers178----------------------179180To dig deeper, possibly to trace code execution, Flask provides a debugger out181of the box (see :ref:`debug-mode`).  If you would like to use another Python182debugger, note that debuggers interfere with each other.  You have to set some183options in order to use your favorite debugger:184185* ``debug``        - whether to enable debug mode and catch exceptions186* ``use_debugger`` - whether to use the internal Flask debugger187* ``use_reloader`` - whether to reload and fork the process on exception188189``debug`` must be True (i.e., exceptions must be caught) in order for the other190two options to have any value.191192If you're using Aptana/Eclipse for debugging you'll need to set both193``use_debugger`` and ``use_reloader`` to False.194195A possible useful pattern for configuration is to set the following in your196config.yaml (change the block as appropriate for your application, of course)::197198   FLASK:199       DEBUG: True200       DEBUG_WITH_APTANA: True201202Then in your application's entry-point (main.py), you could have something like::203204   if __name__ == "__main__":205       # To allow aptana to receive errors, set use_debugger=False206       app = create_app(config="config.yaml")207208       if app.debug: use_debugger = True209       try:210           # Disable Flask's debugger if external debugger is requested211           use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))212       except:213           pass214       app.run(use_debugger=use_debugger, debug=app.debug,215               use_reloader=use_debugger, host='0.0.0.0')