Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

215 lines · 7.9 KiB

Last changed by

Merge pull request #2556 from accraze/patch-1Hsiaoming Yangbefore adoptionb786585

History of this file

Take it

The walk stopped after 200 commits: lines older than d2a46dc point at it.

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 1–44why, one step back
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://www.getsentry.com/>`_ 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://getsentry.com/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.44

Merge pull request #2556 from accraze/patch-1Hsiaoming Yangbefore adoptionb786585

line 45why, one step back
45To use Sentry you need to install the `raven` client with extra `flask` dependencies::

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 46why, one step back
46

Merge pull request #2556 from accraze/patch-1Hsiaoming Yangbefore adoptionb786585

line 47why, one step back
47 $ pip install raven[flask]

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 48–78why, one step back
48
49And 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.78

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 79–81why, one step back
79An error handler is a normal view function that return a response, but instead
80of being registered for a route, it is registered for an exception or HTTP81status code that would is raised while trying to handle a request.

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 82–85why, one step back
82
83Registering84```````````85

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 86–89why, one step back
86Register handlers by decorating a function with
87: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. ::

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 90–92why, one step back
90
91 @app.errorhandler(werkzeug.exceptions.BadRequest)92 def handle_bad_request(e):

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

line 93why, one step back
93 return 'bad request!', 400

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 94why, one step back
94

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 95–96why, one step back
95 # or, without the decorator
96 app.register_error_handler(400, handle_bad_request)

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 97–98why, one step back
97
98:exc:`werkzeug.exceptions.HTTPException` subclasses like

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 99–100why, one step back
99:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable
100when registering handlers. (``BadRequest.code == 400``)

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 101why, one step back
101

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 102–105why, one step back
102Non-standard HTTP codes cannot be registered by code because they are not known
103by Werkzeug. Instead, define a subclass of104:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and105register and raise that exception class. ::

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 106why, one step back
106

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 107–109why, one step back
107 class InsufficientStorage(werkzeug.exceptions.HTTPException):
108 code = 507109 description = 'Not enough storage space.'

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 110why, one step back
110

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

line 111why, one step back
111 app.register_error_handler(InsuffcientStorage, handle_507)

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 112why, one step back
112

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 113–119why, one step back
113 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.119

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 120–122why, one step back
120Handling
121````````122

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 123–128why, one step back
123When an exception is caught by Flask while handling a request, it is first
124looked 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.

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 129why, one step back
129

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

line 130why, one step back
130For example, if an instance of :exc:`ConnectionRefusedError` is raised, and a handler

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 131why, one step back
131is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,

Merge pull request #2350 from davidism/errorhandlerDavid Lordbefore adoptionc7f433c

lines 132–144why, one step back
132the more specific :exc:`ConnectionRefusedError` handler is called with the
133exception 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.

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 145why, one step back
145

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 146–147why, one step back
146Logging
147-------

fix doc build errorDavid Lordbefore adoptiond2a46dc

line 148why, one step back
148

Merge pull request #2436 from davidism/loggingDavid Lordbefore adoptionc74f469

lines 149–150why, one step back
149See :ref:`logging` for information on how to log exceptions, such as by
150emailing them to admins.

fix doc build errorDavid Lordbefore adoptiond2a46dc

lines 151–215why, one step back
151
152153Debugging 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')