errorhandling.rst
This file
Path
docs/errorhandling.rst
213 lines · 8.0 KiB
Last changed by
Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
History of this fileTake 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.141142.. versionchanged:: 0.11143144 Handlers are prioritized by specificity of the exception classes they are145 registered for instead of the order they are registered in.146147Logging148-------149150See :ref:`logging` for information on how to log exceptions, such as by151emailing them to admins.152153154Debugging Application Errors155============================156157For production applications, configure your application with logging and158notifications as described in :ref:`application-errors`. This section provides159pointers when debugging deployment configuration and digging deeper with a160full-featured Python debugger.161162163When in Doubt, Run Manually164---------------------------165166Having problems getting your application configured for production? If you167have shell access to your host, verify that you can run your application168manually from the shell in the deployment environment. Be sure to run under169the same user account as the configured deployment to troubleshoot permission170issues. You can use Flask's builtin development server with `debug=True` on171your production host, which is helpful in catching configuration issues, but172**be sure to do this temporarily in a controlled environment.** Do not run in173production with `debug=True`.174175176.. _working-with-debuggers:177178Working with Debuggers179----------------------180181To dig deeper, possibly to trace code execution, Flask provides a debugger out182of the box (see :ref:`debug-mode`). If you would like to use another Python183debugger, note that debuggers interfere with each other. You have to set some184options in order to use your favorite debugger:185186* ``debug`` - whether to enable debug mode and catch exceptions187* ``use_debugger`` - whether to use the internal Flask debugger188* ``use_reloader`` - whether to reload and fork the process if modules189 were changed190191``debug`` must be True (i.e., exceptions must be caught) in order for the other192two options to have any value.193194If you're using Aptana/Eclipse for debugging you'll need to set both195``use_debugger`` and ``use_reloader`` to False.196197A possible useful pattern for configuration is to set the following in your198config.yaml (change the block as appropriate for your application, of course)::199200 FLASK:201 DEBUG: True202 DEBUG_WITH_APTANA: True203204Then in your application's entry-point (main.py),205you could have something like::206207 if __name__ == "__main__":208 # To allow aptana to receive errors, set use_debugger=False209 app = create_app(config="config.yaml")210211 use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))212 app.run(use_debugger=use_debugger, debug=app.debug,213 use_reloader=use_debugger, host='0.0.0.0')