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
The walk stopped after 200 commits: lines older than 8e2ef5b point at it.
Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 1–36why, one step back1.. _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 `SentryUpdate sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
line 37why, one step back37<https://sentry.io/>`_ for dealing with application errors. It'sFix typo in docs (#2419)asmith26before adoption8e2ef5b
line 38why, one step back38available as an Open Source project `on GitHubUpdate sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
lines 39–40why, one step back39<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version40<https://sentry.io/signup/>`_ which you can try for free. SentryFix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 41–44why, one step back41aggregates duplicate errors, captures the full stack trace and local42variables for debugging, and sends you mails based on new errors or43frequency thresholds.44Update sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
line 45why, one step back45To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::Fix typo in docs (#2419)asmith26before adoption8e2ef5b
line 46why, one step back46Update sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
line 47why, one step back47 $ pip install sentry-sdk[flask]Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 48–50why, one step back4849And then add this to your Flask app::50Update sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
lines 51–52why, one step back51 import sentry_sdk52 from sentry_sdk.integrations.flask import FlaskIntegrationMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
line 53why, one step back53Update sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
line 54why, one step back54 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 55–58why, one step back5556The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get57from your Sentry installation.58Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 59–61why, one step back59After installation, failures leading to an Internal Server Error60are automatically reported to Sentry and from there you can61receive error notifications.Update sentry error handling documentation (#2990)Adam Walshbefore adoption3bf8091
line 62why, one step back62Fixes for sentry docs (#2991)Markus Unterwaditzerbefore adoption3394191
lines 63–69why, one step back63Follow-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/>`_.Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 70–78why, one step back7071.. _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.78Merge pull request #2917 from garenchan/docs1Hsiaoming Yangbefore adoptiond5665e4
line 79why, one step back79An error handler is a normal view function that returns a response, but insteadFix typo in docs (#2419)asmith26before adoption8e2ef5b
line 80why, one step back80of being registered for a route, it is registered for an exception or HTTPMerge pull request #2917 from garenchan/docs1Hsiaoming Yangbefore adoptiond5665e4
line 81why, one step back81status code that would be raised while trying to handle a request.Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 82–110why, one step back8283Registering84```````````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.'110Merge pull request #3041 from obestwalter/patch-1David Lordbefore adoption62621ba
line 111why, one step back111 app.register_error_handler(InsufficientStorage, handle_507)Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 112–129why, one step back112113 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.129Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 130–132why, one step back130For example, if an instance of :exc:`ConnectionRefusedError` is raised,131and a handler is registered for :exc:`ConnectionError` and132:exc:`ConnectionRefusedError`,Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 133–146why, one step back133the 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.146Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469
lines 147–148why, one step back147Logging148-------Fix typo in docs (#2419)asmith26before adoption8e2ef5b
line 149why, one step back149Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469
lines 150–151why, one step back150See :ref:`logging` for information on how to log exceptions, such as by151emailing them to admins.Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 152–187why, one step back152153154Debugging 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 debuggerMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 188–189why, one step back188* ``use_reloader`` - whether to reload and fork the process if modules189 were changedFix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 190–203why, one step back190191``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: True203Merge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
lines 204–205why, one step back204Then in your application's entry-point (main.py),205you could have something like::Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 206–210why, one step back206207 if __name__ == "__main__":208 # To allow aptana to receive errors, set use_debugger=False209 app = create_app(config="config.yaml")210Merge pull request #2917 from garenchan/docs1Hsiaoming Yangbefore adoptiond5665e4
line 211why, one step back211 use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))Fix typo in docs (#2419)asmith26before adoption8e2ef5b
lines 212–213why, one step back212 app.run(use_debugger=use_debugger, debug=app.debug,213 use_reloader=use_debugger, host='0.0.0.0')