Skip to content
Myr

Merge pull request #3669 from ebonnecab/error-docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Error Docs Revision/Consolidation

authored by David Lord · committed by GitHub · parents f31a8ce, 89d1487 · Browse files · 5 files+396 added−429 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+396 added−429 removed

  • other:+396 added−429 removed

5 files+396 added−429 removed

modified:docs/blueprints.rst+3 added-2 removed
240 unmodified lines
241242This will link to ``admin.index`` for instance in case the current request243was dispatched to any other admin blueprint endpoint.244245Error Handlers246--------------245246Blueprint Error Handlers247------------------------248249Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`250application object, so it is easy to make Blueprint-specific custom error251pages.252
25 unmodified lines
added:docs/debugging.rst+97 added
1Debugging Application Errors2============================345In Production6-------------78**Do not run the development server, or enable the built-in debugger, in9a production environment.** The debugger allows executing arbitrary10Python code from the browser. It's protected by a pin, but that should11not be relied on for security.1213Use an error logging tool, such as Sentry, as described in14:ref:`error-logging-tools`, or enable logging and notifications as15described in :doc:`/logging`.1617If you have access to the server, you could add some code to start an18external debugger if ``request.remote_addr`` matches your IP. Some IDE19debuggers also have a remote mode so breakpoints on the server can be20interacted with locally. Only enable a debugger temporarily.212223The Built-In Debugger24---------------------2526The built-in Werkzeug development server provides a debugger which shows27an interactive traceback in the browser when an unhandled error occurs28during a request. This debugger should only be used during development.2930.. image:: _static/debugger.png31 :align: center32 :class: screenshot33 :alt: screenshot of debugger in action3435.. warning::3637 The debugger allows executing arbitrary Python code from the38 browser. It is protected by a pin, but still represents a major39 security risk. Do not run the development server or debugger in a40 production environment.4142To enable the debugger, run the development server with the43``FLASK_ENV`` environment variable set to ``development``. This puts44Flask in debug mode, which changes how it handles some errors, and45enables the debugger and reloader.4647.. code-block:: text4849 $ export FLASK_ENV=development50 $ flask run5152``FLASK_ENV`` can only be set as an environment variable. When running53from Python code, passing ``debug=True`` enables debug mode, which is54mostly equivalent. Debug mode can be controled separately from55``FLASK_ENV`` with the ``FLASK_DEBUG`` environment variable as well.5657.. code-block:: python5859 app.run(debug=True)6061:doc:`/server` and :doc:`/cli` have more information about running the62debugger, debug mode, and development mode. More information about the63debugger can be found in the `Werkzeug documentation64<https://werkzeug.palletsprojects.com/debug/>`__.656667External Debuggers68------------------6970External debuggers, such as those provided by IDEs, can offer a more71powerful debugging experience than the built-in debugger. They can also72be used to step through code during a request before an error is raised,73or if no error is raised. Some even have a remote mode so you can debug74code running on another machine.7576When using an external debugger, the app should still be in debug mode,77but it can be useful to disable the built-in debugger and reloader,78which can interfere.7980When running from the command line:8182.. code-block:: text8384 $ export FLASK_ENV=development85 $ flask run --no-debugger --no-reload8687When running from Python:8889.. code-block:: python9091 app.run(debug=True, use_debugger=False, use_reloader=False)9293Disabling these isn't required, an external debugger will continue to94work with the following caveats. If the built-in debugger is not95disabled, it will catch unhandled exceptions before the external96debugger can. If the reloader is not disabled, it could cause an97unexpected reload if code changes during debugging.
modified:docs/errorhandling.rst+270 added-386 removed
1Handling Application Errors2===========================34.. versionadded:: 0.356Applications fail, servers fail. Sooner or later you will see an exception7in production. Even if your code is 100% correct, you will still see8exceptions from time to time. Why? Because everything else involved will9fail. Here are some situations where perfectly fine code can lead to server4Applications fail, servers fail. Sooner or later you will see an exception5in production. Even if your code is 100% correct, you will still see6exceptions from time to time. Why? Because everything else involved will7fail. Here are some situations where perfectly fine code can lead to server8errors:910- the client terminated the request early and the application was still11 reading from the incoming data
3 unmodified lines
15- a backend server overloaded16- a programming error in a library you are using17- network connection of the server to another system failed1821And that's just a small sample of issues you could be facing. So how do we22deal with that sort of problem? By default if your application runs in19And that's just a small sample of issues you could be facing. So how do we20deal with that sort of problem? By default if your application runs in21production mode, and an exception is raised Flask will display a very simple22page for you and log the exception to the :attr:`~flask.Flask.logger`.2324But there is more you can do, and we will cover some better setups to deal25with errors including custom exceptions and 3rd party tools.262730.. _common-error-codes:28.. _error-logging-tools:2932Common Error Codes33``````````````````30Error Logging Tools31-------------------3235The following error codes are some that are often displayed to the user,36even if the application behaves correctly:33Sending error mails, even if just for critical ones, can become34overwhelming if enough users are hitting the error and log files are35typically never looked at. This is why we recommend using `Sentry36<https://sentry.io/>`_ for dealing with application errors. It's37available as an Open Source project `on GitHub38<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version39<https://sentry.io/signup/>`_ which you can try for free. Sentry40aggregates duplicate errors, captures the full stack trace and local41variables for debugging, and sends you mails based on new errors or42frequency thresholds.4338*400 Bad Request*39 When the server will not process the request due to something that40 the server perceives to be a client error. Such as malformed request41 syntax, missing query parameters, etc.44To use Sentry you need to install the ``sentry-sdk`` client with extra45``flask`` dependencies.4643*403 Forbidden*44 If you have some kind of access control on your website, you will have45 to send a 403 code for disallowed resources. So make sure the user46 is not lost when they try to access a forbidden resource.47.. code-block:: text4848*404 Not Found*49 The good old "chap, you made a mistake typing that URL" message. So50 common that even novices to the internet know that 404 means: damn,51 the thing I was looking for is not there. It's a very good idea to52 make sure there is actually something useful on a 404 page, at least a53 link back to the index.49 $ pip install sentry-sdk[flask]5055*410 Gone*56 Did you know that there the "404 Not Found" has a brother named "41057 Gone"? Few people actually implement that, but the idea is that58 resources that previously existed and got deleted answer with 41059 instead of 404. If you are not deleting documents permanently from60 the database but just mark them as deleted, do the user a favour and61 use the 410 code instead and display a message that what they were62 looking for was deleted for all eternity.51And then add this to your Flask app:5264*500 Internal Server Error*65 Usually happens on programming errors or if the server is overloaded.66 A terribly good idea is to have a nice page there, because your67 application *will* fail sooner or later.53.. code-block:: python5455 import sentry_sdk56 from sentry_sdk.integrations.flask import FlaskIntegration5758 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])5971Default Error Handling72``````````````````````60The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you61get from your Sentry installation.6263After installation, failures leading to an Internal Server Error64are automatically reported to Sentry and from there you can65receive error notifications.6667See also:6869- Sentry also supports catching errors from a worker queue70 (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs71 <https://docs.sentry.io/platforms/python/>`__ for more information.72- `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`__73- `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`__747576Error Handlers77--------------7879When an error occurs in Flask, an appropriate `HTTP status code80<https://developer.mozilla.org/en-US/docs/Web/HTTP/Status>`__ will be81returned. 400-499 indicate errors with the client's request data, or82about the data requested. 500-599 indicate errors with the server or83application itself.8485You might want to show custom error pages to the user when an error occurs.86This can be done by registering error handlers.8788An error handler is a function that returns a response when a type of error is89raised, similar to how a view is a function that returns a response when a90request URL is matched. It is passed the instance of the error being handled,91which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.9293The status code of the response will not be set to the handler's code. Make94sure to provide the appropriate HTTP status code when returning a response from95a handler.969798Registering99```````````100101Register handlers by decorating a function with102:meth:`~flask.Flask.errorhandler`. Or use103:meth:`~flask.Flask.register_error_handler` to register the function later.104Remember to set the error code when returning the response.105106.. code-block:: python107108 @app.errorhandler(werkzeug.exceptions.BadRequest)109 def handle_bad_request(e):110 return 'bad request!', 400111112 # or, without the decorator113 app.register_error_handler(400, handle_bad_request)114115:exc:`werkzeug.exceptions.HTTPException` subclasses like116:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable117when registering handlers. (``BadRequest.code == 400``)118119Non-standard HTTP codes cannot be registered by code because they are not known120by Werkzeug. Instead, define a subclass of121:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and122register and raise that exception class.123124.. code-block:: python125126 class InsufficientStorage(werkzeug.exceptions.HTTPException):127 code = 507128 description = 'Not enough storage space.'129130 app.register_error_handler(InsufficientStorage, handle_507)131132 raise InsufficientStorage()133134Handlers can be registered for any exception class, not just135:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status136codes. Handlers can be registered for a specific class, or for all subclasses137of a parent class.138139140Handling141````````142143When building a Flask application you *will* run into exceptions. If some part144of your code breaks while handling a request (and you have no error handlers76registered) an "500 Internal Server Error"145registered), a "500 Internal Server Error"146(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.78Similarly, if a request is sent to an unregistered route a "404 Not Found"79(:exc:`~werkzeug.exceptions.NotFound`) error will occur. If a route receives an80unallowed request method a "405 Method Not Allowed"147Similarly, "404 Not Found"148(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.149If a route receives an unallowed request method, a "405 Method Not Allowed"150(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all151subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by152default in Flask.153154Flask gives you to the ability to raise any HTTP exception registered by86werkzeug. However, as the default HTTP exceptions return simple exception87pages, Flask also offers the opportunity to customise these HTTP exceptions via88custom error handlers as well as to add exception handlers for builtin and89custom exceptions.155Werkzeug. However, the default HTTP exceptions return simple exception156pages. You might want to show custom error pages to the user when an error occurs.157This can be done by registering error handlers.15891When an exception is caught by Flask while handling a request, it is first92looked up by code. If no handler is registered for the code, it is looked up93by its class hierarchy; the most specific handler is chosen. If no handler is94registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a159When Flask catches an exception while handling a request, it is first looked up by code.160If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.161If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a162generic message about their code, while other exceptions are converted to a163generic "500 Internal Server Error".164165For example, if an instance of :exc:`ConnectionRefusedError` is raised,
7 unmodified lines
173because the 404 occurs at the routing level before the blueprint can be174determined.175176177Generic Exception Handlers178``````````````````````````179111.. _handling-errors:180It is possible to register error handlers for very generic base classes181such as ``HTTPException`` or even ``Exception``. However, be aware that182these will catch more than you might expect.183113Handling Errors114```````````````184For example, an error handler for ``HTTPException`` might be useful for turning185the default HTML errors pages into JSON. However, this186handler will trigger for things you don't cause directly, such as 404187and 405 errors during routing. Be sure to craft your handler carefully188so you don't lose information about the HTTP error.189116Sometimes when building a Flask application, you might want to raise a117:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that118something is wrong with the request. Fortunately, Flask comes with a handy119:func:`~flask.abort` function that aborts a request with a HTTP error from120werkzeug as desired.121122Consider the code below, we might have a user profile route, but if the user123fails to pass a username we raise a "400 Bad Request" and if the user passes a124username but we can't find it, we raise a "404 Not Found".125190.. code-block:: python191128 from flask import abort, render_template, request192 from flask import json193 from werkzeug.exceptions import HTTPException194130 # a username needs to be supplied in the query args131 # a successful request would be like /profile?username=jack132 @app.route("/profile")133 def user_profile():134 username = request.arg.get("username")135 # if a username isn't supplied in the request, return a 400 bad request136 if username is None:137 abort(400)195 @app.errorhandler(HTTPException)196 def handle_exception(e):197 """Return JSON instead of HTML for HTTP errors."""198 # start with the correct headers and status code from the error199 response = e.get_response()200 # replace the body with JSON201 response.data = json.dumps({202 "code": e.code,203 "name": e.name,204 "description": e.description,205 })206 response.content_type = "application/json"207 return response208139 user = get_user(username=username)140 # if a user can't be found by their username, return 404 not found141 if user is None:142 abort(404)209An error handler for ``Exception`` might seem useful for changing how210all errors, even unhandled ones, are presented to the user. However,211this is similar to doing ``except Exception:`` in Python, it will212capture *all* otherwise unhandled errors, including all HTTP status213codes.214144 return render_template("profile.html", user=user)215In most cases it will be safer to register handlers for more216specific exceptions. Since ``HTTPException`` instances are valid WSGI217responses, you could also pass them through directly.218146147148.. _custom-error-handlers:149150Custom error handlers151`````````````````````152153The default :exc:`~werkzeug.exceptions.HTTPException` returns a black and white154error page with a basic description, but nothing fancy. Considering155these errors *will* be thrown during the lifetime of your application, it is156highly advisable to customise these exceptions to improve the user experience157of your site. This can be done by registering error handlers.158159An error handler is a normal view function that returns a response, but instead160of being registered for a route, it is registered for an exception or HTTP161status code that would be raised while trying to handle a request.162163It is passed the instance of the error being handled, which is most164likely an integer that represents a :exc:`~werkzeug.exceptions.HTTPException`165status code. For example 500 (an "Internal Server Error") which maps to166:exc:`~werkzeug.exceptions.InternalServerError`.167168It is registered with the :meth:`~flask.Flask.errorhandler`169decorator or the :meth:`~flask.Flask.register_error_handler` to register170the function later. A handler can be registered for a status code,171like 404 or 500, or for an built-in exception class, like KeyError,172or a custom exception class that inherits from Exception or its subclasses.173174The status code of the response will not be set to the handler's code. Make175sure to provide the appropriate HTTP status code when returning a response from176a handler or a 200 OK HTTP code will be sent instead.177219.. code-block:: python220180 from werkzeug.exceptions import InternalServerError221 from werkzeug.exceptions import HTTPException222182 # as a decorator with an int as the exception code183 @app.errorhandler(500)184 def handle_internal_server_error(e):185 # returning 500 with the text sets the error handler's code186 # make sure to provide the appropriate HTTP status code187 # otherwise 200 will be returned as default188 return 'Internal Server Error!', 500223 @app.errorhandler(Exception)224 def handle_exception(e):225 # pass through HTTP errors226 if isinstance(e, HTTPException):227 return e228190 # or, as a decorator with the werkzeug exception for internal server error191 @app.errorhandler(InternalServerError)192 def handle_internal_server_error(e):193 # werkzeug exceptions have a code attribute194 return 'Internal Server Error!', e.code229 # now you're handling non-HTTP exceptions only230 return render_template("500_generic.html", e=e), 500231196 # or, without the decorator197 app.register_error_handler(500, handle_internal_server_error)232Error handlers still respect the exception class hierarchy. If you233register handlers for both ``HTTPException`` and ``Exception``, the234``Exception`` handler will not handle ``HTTPException`` subclasses235because it the ``HTTPException`` handler is more specific.236199 # similarly with a werkzeug exception200 app.register_error_handler(InternalServerError, handle_internal_server_error)237238Unhandled Exceptions239````````````````````240241When there is no error handler registered for an exception, a 500242Internal Server Error will be returned instead. See243:meth:`flask.Flask.handle_exception` for information about this244behavior.245204A handler for "500 Internal Server Error" will not be used when running in205debug mode. Instead, the interactive debugger will be shown.206246If there is an error handler registered for ``InternalServerError``,247this will be invoked. As of Flask 1.1.0, this error handler will always248be passed an instance of ``InternalServerError``, not the original249unhandled error.250210unhandled error. The original error is available as ``e.original_exception``.251The original error is available as ``e.original_exception``.252Until Werkzeug 1.0.0, this attribute will only exist during unhandled253errors, use ``getattr`` to get access it for compatibility.254255.. code-block:: python
8 unmodified lines
264265 # wrapped unhandled error266 return render_template("500_unhandled.html", e=original), 500267268An error handler for "500 Internal Server Error" will be passed uncaught exceptions in269addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.270Instead, the interactive debugger will be shown.271272229Registering Custom Exceptions230-----------------------------273Custom Error Pages274------------------275232You can create your own custom exceptions by subclassing233:exc:`werkzeug.exceptions.HTTPException`. As shown above, integer HTTP codes234are interchangable when registering handlers. (``BadRequest.code == 400``)276Sometimes when building a Flask application, you might want to raise a277:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that278something is wrong with the request. Fortunately, Flask comes with a handy279:func:`~flask.abort` function that aborts a request with a HTTP error from280werkzeug as desired. It will also provide a plain black and white error page281for you with a basic description, but nothing fancy.282236Non-standard HTTP codes cannot be registered by code because they are not known237by Werkzeug. Instead, define a subclass of238:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and239register and raise that exception class:283Depending on the error code it is less or more likely for the user to284actually see such an error.285286Consider the code below, we might have a user profile route, and if the user287fails to pass a username we can raise a "400 Bad Request". If the user passes a288username and we can't find it, we raise a "404 Not Found".289290.. code-block:: python291243 class InsufficientStorage(werkzeug.exceptions.HTTPException):244 code = 507245 description = 'Not enough storage space.'292 from flask import abort, render_template, request293247 def handle_507(e):248 return 'Not enough storage space!', 507294 # a username needs to be supplied in the query args295 # a successful request would be like /profile?username=jack296 @app.route("/profile")297 def user_profile():298 username = request.arg.get("username")299 # if a username isn't supplied in the request, return a 400 bad request300 if username is None:301 abort(400)302250 app.register_error_handler(InsufficientStorage, handle_507)303 user = get_user(username=username)304 # if a user can't be found by their username, return 404 not found305 if user is None:306 abort(404)307252 # during an request253 raise InsufficientStorage()308 return render_template("profile.html", user=user)309255Handlers can be registered for any exception class that inherits from Exception.310Here is another example implementation for a "404 Page Not Found" exception:311312.. code-block:: python313258Unhandled Exceptions259--------------------314 from flask import render_template315261If an exception is raised in the code while Flask is handling a request and262there is no error handler registered for that exception, a "500 Internal Server263Error" will be returned instead. See :meth:`flask.Flask.handle_exception` for264information about this behavior.316 @app.errorhandler(404)317 def page_not_found(e):318 # note that we set the 404 status explicitly319 return render_template('404.html'), 404320266Custom error pages267------------------321When using :doc:`/patterns/appfactories`:322323.. code-block:: python324325 from flask import Flask, render_template326327 def page_not_found(e):328 return render_template('404.html'), 404329330 def create_app(config_filename):331 app = Flask(__name__)332 app.register_error_handler(404, page_not_found)333 return app334335An example template might be this:336337.. code-block:: html+jinja338339 {% extends "layout.html" %}340 {% block title %}Page Not Found{% endblock %}341 {% block body %}342 <h1>Page Not Found</h1>343 <p>What you were looking for is just not there.344 <p><a href="{{ url_for('index') }}">go somewhere nice</a>345 {% endblock %}346347348Further Examples349````````````````350351The above examples wouldn't actually be an improvement on the default352exception pages. We can create a custom 500.html template like this:353272.. sourcecode:: html+jinja354.. code-block:: html+jinja355356 {% extends "layout.html" %}357 {% block title %}Internal Server Error{% endblock %}358 {% block body %}
12 unmodified lines
371 def internal_server_error(e):372 # note that we set the 500 status explicitly373 return render_template('500.html'), 500374375When using :doc:`/patterns/appfactories`:376294When using the :doc:`/patterns/appfactories`:295377.. code-block:: python378298379 from flask import Flask, render_template380381 def internal_server_error(e):382 return render_template('500.html'), 500
2 unmodified lines
385 app = Flask(__name__)386 app.register_error_handler(500, internal_server_error)387 return app388309389When using :doc:`/blueprints`:390391.. code-block:: python392
9 unmodified lines
402 # or with register_error_handler403 blog.register_error_handler(500, internal_server_error)404405406Blueprint Error Handlers407------------------------408328In blueprints errorhandlers will simply work as expected; however, there is a caveat329concerning handlers for 404 and 405 exceptions. These errorhandlers are only330invoked from an appropriate ``raise`` statement or a call to ``abort`` in another331of the blueprint's view functions; they are not invoked by, e.g., an invalid URL332access. This is because the blueprint does not "own" a certain URL space, so333the application instance has no way of knowing which blueprint error handler it334should run if given an invalid URL. If you would like to execute different335handling strategies for these errors based on URL prefixes, they may be defined336at the application level using the ``request`` proxy object:409In :doc:`/blueprints`, most error handlers will work as expected.410However, there is a caveat concerning handlers for 404 and 405411exceptions. These error handlers are only invoked from an appropriate412``raise`` statement or a call to ``abort`` in another of the blueprint's413view functions; they are not invoked by, e.g., an invalid URL access.414415This is because the blueprint does not "own" a certain URL space, so416the application instance has no way of knowing which blueprint error417handler it should run if given an invalid URL. If you would like to418execute different handling strategies for these errors based on URL419prefixes, they may be defined at the application level using the420``request`` proxy object.421422.. code-block:: python423424 from flask import jsonify, render_template425
8 unmodified lines
434 else:435 # otherwise we return our generic site-wide 404 page436 return render_template("404.html"), 404437354438 @app.errorhandler(405)439 def method_not_allowed(e):440 # if a request has the wrong method to our API441 if request.path.startswith('/api/'):
3 unmodified lines
445 # otherwise we return a generic site-wide 405 page446 return render_template("405.html"), 405447448449Returning API Errors as JSON450----------------------------451367More information on error handling with blueprint can be found in368:doc:`/blueprints`.369370371Returning API errors as JSON372````````````````````````````373374When building APIs in Flask, some developers realise that the builtin452When building APIs in Flask, some developers realise that the built-in453exceptions are not expressive enough for APIs and that the content type of454:mimetype:`text/html` they are emitting is not very useful for API consumers.455456Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON457responses to API errors. :func:`~flask.abort` is called380with a ``description`` parameter. The errorhandler will458with a ``description`` parameter. The error handler will459use that as the JSON error message, and set the status code to 404.460461.. code-block:: python462
11 unmodified lines
474 abort(404, description="Resource not found")475476 return jsonify(resource)477400401402We can also create custom exception classes; for instance, for an API we can403introduce a new custom exception that can take a proper human readable message,478We can also create custom exception classes. For instance, we can479introduce a new custom exception for an API that can take a proper human readable message,480a status code for the error and some optional payload to give more context481for the error.482483This is a simple example:
34 unmodified lines
518 raise InvalidAPIUsage("No such user!", status_code=404)519520 return jsonify(user.to_dict())521446447A view can now raise that exception with an error message. Additionally522A view can now raise that exception with an error message. Additionally523some extra payload can be provided as a dictionary through the `payload`524parameter.525526452Generic Exception Handlers453``````````````````````````454455It is possible to register error handlers for very generic base classes456such as ``HTTPException`` or even ``Exception``. However, be aware that457these will catch more than you might expect.458459An error handler for ``HTTPException`` might be useful for turning460the default HTML errors pages into JSON, for example. However, this461handler will trigger for things you don't cause directly, such as 404462and 405 errors during routing. Be sure to craft your handler carefully463so you don't lose information about the HTTP error.464465.. code-block:: python466467 from flask import json468 from werkzeug.exceptions import HTTPException469470 @app.errorhandler(HTTPException)471 def handle_exception(e):472 """Return JSON instead of HTML for HTTP errors."""473 # start with the correct headers and status code from the error474 response = e.get_response()475 # replace the body with JSON476 response.data = json.dumps({477 "code": e.code,478 "name": e.name,479 "description": e.description,480 })481 response.content_type = "application/json"482 return response483484 # or using jsonify485 @app.errorhandler(HTTPException)486 def handle_exception(e):487 return jsonify("code": e.code, "name": e.name, "description": e.description), e.code488489490An error handler for ``Exception`` might seem useful for changing how491all errors, even unhandled ones, are presented to the user. However,492this is similar to doing ``except Exception:`` in Python, it will493capture *all* otherwise unhandled errors, including all HTTP status494codes. In most cases it will be safer to register handlers for more495specific exceptions. Since ``HTTPException`` instances are valid WSGI496responses, you could also pass them through directly.497498.. code-block:: python499500 from werkzeug.exceptions import HTTPException501502 @app.errorhandler(Exception)503 def handle_exception(e):504 # pass through HTTP errors505 if isinstance(e, HTTPException):506 return e507508 # now you're handling non-HTTP exceptions only509 return render_template("500_generic.html", e=e), 500510511Error handlers still respect the exception class hierarchy. If you512register handlers for both ``HTTPException`` and ``Exception``, the513``Exception`` handler will not handle ``HTTPException`` subclasses514because it the ``HTTPException`` handler is more specific.515516517Generic Error Pages518-------------------519520If we pass in the exception into a template as below:521522.. code-block:: python523524 from werkzeug.exceptions import HTTPException525526 @app.errorhandler(HTTPException)527 def handle_exception(e):528 return render_template("exception.html", e=e), e.code529530531532.. sourcecode:: html+jinja533534 {% extends "layout.html" %}535 {% block title %}{{ e.name }}{% endblock %}536 {% block body %}537 <h1>{{ e.code }} {{ e.name }}</h1>538 <p>{{ e.description }}</p>539 <p><a href="{{ url_for('index') }}">Go home</a>540 {% endblock %}541542543544Debugging Application Errors545````````````````````````````546547For production applications, configure your application with logging and548notifications as described in :doc:`/logging`. This section provides549pointers when debugging deployment configuration and digging deeper with a550full-featured Python debugger.551527Logging528-------529555See :doc:`/logging` for information on how to log exceptions, such as by556emailing them to admins.530See :doc:`/logging` for information about how to log exceptions, such as531by emailing them to admins.532533534Debugging535---------536560When in Doubt, Run Manually561---------------------------562563Having problems getting your application configured for production? If you564have shell access to your host, verify that you can run your application565manually from the shell in the deployment environment. Be sure to run under566the same user account as the configured deployment to troubleshoot permission567issues. You can use Flask's builtin development server with `debug=True` on568your production host, which is helpful in catching configuration issues, but569**be sure to do this temporarily in a controlled environment.** Do not run in570production with `debug=True`.571572573.. _working-with-debuggers:574575Working with Debuggers576----------------------577578To dig deeper, possibly to trace code execution, Flask provides a debugger out579of the box (see :ref:`debug-mode`). If you would like to use another Python580debugger, note that debuggers interfere with each other. You have to set some581options in order to use your favorite debugger:582583* ``debug`` - whether to enable debug mode and catch exceptions584* ``use_debugger`` - whether to use the internal Flask debugger585* ``use_reloader`` - whether to reload and fork the process if modules586 were changed587588``debug`` must be True (i.e., exceptions must be caught) in order for the other589two options to have any value.590591If you're using Aptana/Eclipse for debugging you'll need to set both592``use_debugger`` and ``use_reloader`` to False.593594A possible useful pattern for configuration is to set the following in your595config.yaml (change the block as appropriate for your application, of course)::596597 FLASK:598 DEBUG: True599 DEBUG_WITH_APTANA: True600601Then in your application's entry-point (main.py),602you could have something like::603604 if __name__ == "__main__":605 # To allow aptana to receive errors, set use_debugger=False606 app = create_app(config="config.yaml")607608 use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))609 app.run(use_debugger=use_debugger, debug=app.debug,610 use_reloader=use_debugger, host='0.0.0.0')611612613.. _error-logging-tools:614615616Error Logging Tools617-------------------618619Sending error mails, even if just for critical ones, can become620overwhelming if enough users are hitting the error and log files are621typically never looked at. This is why we recommend using `Sentry622<https://sentry.io/>`_ for dealing with application errors. It's623available as an Open Source project `on GitHub624<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version625<https://sentry.io/signup/>`_ which you can try for free. Sentry626aggregates duplicate errors, captures the full stack trace and local627variables for debugging, and sends you mails based on new errors or628frequency thresholds.629630To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::631632 $ pip install sentry-sdk[flask]633634And then add this to your Flask app::635636 import sentry_sdk637 from sentry_sdk.integrations.flask import FlaskIntegration638639 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])640641The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get642from your Sentry installation.643644After installation, failures leading to an Internal Server Error645are automatically reported to Sentry and from there you can646receive error notifications.647648Follow-up reads:649650* Sentry also supports catching errors from your worker queue (RQ, Celery) in a651 similar fashion. See the `Python SDK docs652 <https://docs.sentry.io/platforms/python/>`_ for more information.653* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_654* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.537See :doc:`/debugging` for information about how to debug errors in538development and production.
modified:docs/index.rst+1 added
42 unmodified lines
43 tutorial/index44 templating45 testing46 errorhandling47 debugging48 logging49 config50 signals51 views
39 unmodified lines
modified:docs/quickstart.rst+25 added-41 removed
109 unmodified lines
110111The most common reason is a typo or because you did not actually create an112``app`` object.113114.. _debug-mode:114115Debug Mode116----------117119(Want to just log errors and stack traces? See :doc:`errorhandling`)118The ``flask run`` command can do more than just start the development119server. By enabling debug mode, the server will automatically reload if120code changes, and will show an interactive debugger in the browser if an121error occurs during a request.122121The :command:`flask` script is nice to start a local development server, but122you would have to restart it manually after each change to your code.123That is not very nice and Flask can do better. If you enable debug124support the server will reload itself on code changes, and it will also125provide you with a helpful debugger if things go wrong.123.. image:: _static/debugger.png124 :align: center125 :class: screenshot126 :alt: The interactive debugger in action.127127To enable all development features (including debug mode) you can export128the ``FLASK_ENV`` environment variable and set it to ``development``129before running the server::128.. warning::129131 $ export FLASK_ENV=development132 $ flask run130 The debugger allows executing arbitrary Python code from the131 browser. It is protected by a pin, but still represents a major132 security risk. Do not run the development server or debugger in a133 production environment.134134(On Windows you need to use ``set`` instead of ``export``.)135To enable all development features, set the ``FLASK_ENV`` environment136variable to ``development`` before calling ``flask run``.137136This does the following things:138.. code-block:: text1391381. it activates the debugger1392. it activates the automatic reloader1403. it enables the debug mode on the Flask application.140 $ export FLASK_ENV=development141 $ flask run142142You can also control debug mode separately from the environment by143exporting ``FLASK_DEBUG=1``.143See also:144145There are more parameters that are explained in :doc:`/server`.145- :doc:`/server` and :doc:`/cli` for information about running in146 development mode.147- :doc:`/debugging` for information about using the built-in debugger148 and other debuggers.149- :doc:`/logging` and :doc:`/errorhandling` to log errors and display150 nice error pages.151147.. admonition:: Attention152149 Even though the interactive debugger does not work in forking environments150 (which makes it nearly impossible to use on production servers), it still151 allows the execution of arbitrary code. This makes it a major security risk152 and therefore it **must never be used on production machines**.153154Screenshot of the debugger in action:155156.. image:: _static/debugger.png157 :align: center158 :class: screenshot159 :alt: screenshot of debugger in action160161More information on using the debugger can be found in the `Werkzeug162documentation`_.163164.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debugger165166Have another debugger in mind? See :ref:`working-with-debuggers`.167168153HTML Escaping154-------------155156When returning HTML (the default response type in Flask), any
747 unmodified lines