Skip to content
Myr

Merge pull request #3594 from jackwardell/consolidating-error-pages-docs

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

consolidate error handling docs

authored by David Lord · committed by GitHub · parents 165f059, 59b0b85 · Browse files · 5 files+460 added−288 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+460 added−288 removed

  • other:+460 added−288 removed

5 files+460 added−288 removed

deleted:docs/patterns/apierrors.rst-63 removed
1Implementing API Exceptions2===========================34It's very common to implement RESTful APIs on top of Flask. One of the5first things that developers run into is the realization that the builtin6exceptions are not expressive enough for APIs and that the content type of7:mimetype:`text/html` they are emitting is not very useful for API consumers.89The better solution than using ``abort`` to signal errors for invalid API10usage is to implement your own exception type and install an error handler11for it that produces the errors in the format the user is expecting.1213Simple Exception Class14----------------------1516The basic idea is to introduce a new exception that can take a proper17human readable message, a status code for the error and some optional18payload to give more context for the error.1920This is a simple example::2122 from flask import jsonify2324 class InvalidUsage(Exception):25 status_code = 4002627 def __init__(self, message, status_code=None, payload=None):28 Exception.__init__(self)29 self.message = message30 if status_code is not None:31 self.status_code = status_code32 self.payload = payload3334 def to_dict(self):35 rv = dict(self.payload or ())36 rv['message'] = self.message37 return rv3839A view can now raise that exception with an error message. Additionally40some extra payload can be provided as a dictionary through the `payload`41parameter.4243Registering an Error Handler44----------------------------4546At that point views can raise that error, but it would immediately result47in an internal server error. The reason for this is that there is no48handler registered for this error class. That however is easy to add::4950 @app.errorhandler(InvalidUsage)51 def handle_invalid_usage(error):52 response = jsonify(error.to_dict())53 response.status_code = error.status_code54 return response5556Usage in Views57--------------5859Here is how a view can use that functionality::6061 @app.route('/foo')62 def get_foo():63 raise InvalidUsage('This view is gone', status_code=410)
deleted:docs/patterns/errorpages.rst-123 removed
1Custom Error Pages2==================34Flask comes with a handy :func:`~flask.abort` function that aborts a5request with an HTTP error code early. It will also provide a plain black6and white error page for you with a basic description, but nothing fancy.78Depending on the error code it is less or more likely for the user to9actually see such an error.1011Common Error Codes12------------------1314The following error codes are some that are often displayed to the user,15even if the application behaves correctly:1617*404 Not Found*18 The good old "chap, you made a mistake typing that URL" message. So19 common that even novices to the internet know that 404 means: damn,20 the thing I was looking for is not there. It's a very good idea to21 make sure there is actually something useful on a 404 page, at least a22 link back to the index.2324*403 Forbidden*25 If you have some kind of access control on your website, you will have26 to send a 403 code for disallowed resources. So make sure the user27 is not lost when they try to access a forbidden resource.2829*410 Gone*30 Did you know that there the "404 Not Found" has a brother named "41031 Gone"? Few people actually implement that, but the idea is that32 resources that previously existed and got deleted answer with 41033 instead of 404. If you are not deleting documents permanently from34 the database but just mark them as deleted, do the user a favour and35 use the 410 code instead and display a message that what they were36 looking for was deleted for all eternity.3738*500 Internal Server Error*39 Usually happens on programming errors or if the server is overloaded.40 A terribly good idea is to have a nice page there, because your41 application *will* fail sooner or later (see also:42 :doc:`/errorhandling`).434445Error Handlers46--------------4748An error handler is a function that returns a response when a type of error is49raised, similar to how a view is a function that returns a response when a50request URL is matched. It is passed the instance of the error being handled,51which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error52handler for "500 Internal Server Error" will be passed uncaught exceptions in53addition to explicit 500 errors.5455An error handler is registered with the :meth:`~flask.Flask.errorhandler`56decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler57can be registered for a status code, like 404, or for an exception class.5859The status code of the response will not be set to the handler's code. Make60sure to provide the appropriate HTTP status code when returning a response from61a handler.6263A handler for "500 Internal Server Error" will not be used when running in64debug mode. Instead, the interactive debugger will be shown.6566Here is an example implementation for a "404 Page Not Found" exception::6768 from flask import render_template6970 @app.errorhandler(404)71 def page_not_found(e):72 # note that we set the 404 status explicitly73 return render_template('404.html'), 4047475When using the :doc:`appfactories`::7677 from flask import Flask, render_template7879 def page_not_found(e):80 return render_template('404.html'), 4048182 def create_app(config_filename):83 app = Flask(__name__)84 app.register_error_handler(404, page_not_found)85 return app8687An example template might be this:8889.. sourcecode:: html+jinja9091 {% extends "layout.html" %}92 {% block title %}Page Not Found{% endblock %}93 {% block body %}94 <h1>Page Not Found</h1>95 <p>What you were looking for is just not there.96 <p><a href="{{ url_for('index') }}">go somewhere nice</a>97 {% endblock %}9899100Returning API errors as JSON101----------------------------102103When using Flask for web APIs, you can use the same techniques as above104to return JSON responses to API errors. :func:`~flask.abort` is called105with a ``description`` parameter. The :meth:`~flask.errorhandler` will106use that as the JSON error message, and set the status code to 404.107108.. code-block:: python109110 from flask import abort, jsonify111112 @app.errorhandler(404)113 def resource_not_found(e):114 return jsonify(error=str(e)), 404115116 @app.route("/cheese")117 def get_one_cheese():118 resource = get_resource()119120 if resource is None:121 abort(404, description="Resource not found")122123 return jsonify(resource)
modified:docs/patterns/index.rst-2 removed
16 unmodified lines
1718 packages19 appfactories20 appdispatch21 apierrors21 urlprocessors22 distribute23 fabric24 sqlite3
4 unmodified lines
29 wtforms30 templateinheritance31 flashing32 jquery34 errorpages33 lazyloading34 mongoengine35 favicon36 streaming
6 unmodified lines
modified:docs/blueprints.rst+1 added-1 removed
271 unmodified lines
272 return jsonify_error(ex)273 else:274 return ex275276More information on error handling see :doc:`/patterns/errorpages`.276See :doc:`/errorhandling`.
modified:docs/errorhandling.rst+459 added-99 removed
1Application Errors2==================1Handling Application Errors2===========================34.. versionadded:: 0.356Applications fail, servers fail. Sooner or later you will see an exception
12 unmodified lines
19- network connection of the server to another system failed2021And 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 in23production mode, Flask will display a very simple page for you and log the24exception to the :attr:`~flask.Flask.logger`.23production mode, and an exception is raised Flask will display a very simple24page for you and log the exception to the :attr:`~flask.Flask.logger`.2526But there is more you can do, and we will cover some better setups to deal27with errors.27with errors including custom exceptions and 3rd party tools.2829Error Logging Tools30-------------------2932Sending error mails, even if just for critical ones, can become33overwhelming if enough users are hitting the error and log files are34typically never looked at. This is why we recommend using `Sentry35<https://sentry.io/>`_ for dealing with application errors. It's36available as an Open Source project `on GitHub37<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version38<https://sentry.io/signup/>`_ which you can try for free. Sentry39aggregates duplicate errors, captures the full stack trace and local40variables for debugging, and sends you mails based on new errors or41frequency thresholds.30.. _common-error-codes:3143To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::32Common Error Codes33``````````````````3445 $ pip install sentry-sdk[flask]35The following error codes are some that are often displayed to the user,36even if the application behaves correctly:3747And then add this to your Flask app::38*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.4249 import sentry_sdk50 from sentry_sdk.integrations.flask import FlaskIntegration43*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.4752 sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])48*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.5454The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get55from your Sentry installation.55*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.6357After installation, failures leading to an Internal Server Error58are automatically reported to Sentry and from there you can59receive error notifications.64*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.6861Follow-up reads:6963* Sentry also supports catching errors from your worker queue (RQ, Celery) in a64 similar fashion. See the `Python SDK docs65 <https://docs.sentry.io/platforms/python/>`_ for more information.66* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_67* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.7071Default Error Handling72``````````````````````7370Error handlers71--------------74When building a Flask application you *will* run into exceptions. If some part75of your code breaks while handling a request (and you have no error handlers76registered) an "500 Internal Server Error"77(: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"81(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all82subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by83default in Flask.8473You might want to show custom error pages to the user when an error occurs.74This can be done by registering error handlers.85Flask 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.9091When 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 a95generic message about their code, while other exceptions are converted to a96generic "500 Internal Server Error".9798For example, if an instance of :exc:`ConnectionRefusedError` is raised,99and a handler is registered for :exc:`ConnectionError` and100:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`101handler is called with the exception instance to generate the response.102103Handlers registered on the blueprint take precedence over those registered104globally on the application, assuming a blueprint is handling the request that105raises the exception. However, the blueprint cannot handle 404 routing errors106because the 404 occurs at the routing level before the blueprint can be107determined.108109110111.. _handling-errors:112113Handling Errors114```````````````115116Sometimes 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".125126.. code-block:: python127128 from flask import abort, render_template, request129130 # 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)138139 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)143144 return render_template("profile.html", user=user)145146147148.. _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.16280Registering81```````````163It 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`.16783Register handlers by decorating a function with84:meth:`~flask.Flask.errorhandler`. Or use85:meth:`~flask.Flask.register_error_handler` to register the function later.86Remember to set the error code when returning the response. ::168It 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.17388 @app.errorhandler(werkzeug.exceptions.BadRequest)89 def handle_bad_request(e):90 return 'bad request!', 400174The 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.177178.. code-block:: python179180 from werkzeug.exceptions import InternalServerError181182 # 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!', 500189190 # 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.code195196 # or, without the decorator93 app.register_error_handler(400, handle_bad_request)197 app.register_error_handler(500, handle_internal_server_error)19895:exc:`werkzeug.exceptions.HTTPException` subclasses like96:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable97when registering handlers. (``BadRequest.code == 400``)199 # similarly with a werkzeug exception200 app.register_error_handler(InternalServerError, handle_internal_server_error)201202203204A handler for "500 Internal Server Error" will not be used when running in205debug mode. Instead, the interactive debugger will be shown.206207If there is an error handler registered for ``InternalServerError``,208this will be invoked. As of Flask 1.1.0, this error handler will always209be passed an instance of ``InternalServerError``, not the original210unhandled error. The original error is available as ``e.original_exception``.211Until Werkzeug 1.0.0, this attribute will only exist during unhandled212errors, use ``getattr`` to get access it for compatibility.213214.. code-block:: python215216 @app.errorhandler(InternalServerError)217 def handle_500(e):218 original = getattr(e, "original_exception", None)219220 if original is None:221 # direct 500 error, such as abort(500)222 return render_template("500.html"), 500223224 # wrapped unhandled error225 return render_template("500_unhandled.html", e=original), 500226227228229Registering Custom Exceptions230-----------------------------231232You 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``)235236Non-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 and102register and raise that exception class. ::239register and raise that exception class:240241.. code-block:: python242243 class InsufficientStorage(werkzeug.exceptions.HTTPException):244 code = 507245 description = 'Not enough storage space.'246247 def handle_507(e):248 return 'Not enough storage space!', 507249250 app.register_error_handler(InsufficientStorage, handle_507)251252 # during an request253 raise InsufficientStorage()254112Handlers can be registered for any exception class, not just113:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status114codes. Handlers can be registered for a specific class, or for all subclasses115of a parent class.255Handlers can be registered for any exception class that inherits from Exception.256117Handling118````````257120When an exception is caught by Flask while handling a request, it is first121looked up by code. If no handler is registered for the code, it is looked up122by its class hierarchy; the most specific handler is chosen. If no handler is123registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a124generic message about their code, while other exceptions are converted to a125generic 500 Internal Server Error.258Unhandled Exceptions259--------------------260127For example, if an instance of :exc:`ConnectionRefusedError` is raised,128and a handler is registered for :exc:`ConnectionError` and129:exc:`ConnectionRefusedError`,130the more specific :exc:`ConnectionRefusedError` handler is called with the131exception instance to generate the response.261If 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.265133Handlers registered on the blueprint take precedence over those registered134globally on the application, assuming a blueprint is handling the request that135raises the exception. However, the blueprint cannot handle 404 routing errors136because the 404 occurs at the routing level before the blueprint can be137determined.266Custom error pages267------------------268269The above examples wouldn't actually be an improvement on the default270exception pages. We can create a custom 500.html template like this:271272.. sourcecode:: html+jinja273274 {% extends "layout.html" %}275 {% block title %}Internal Server Error{% endblock %}276 {% block body %}277 <h1>Internal Server Error</h1>278 <p>Oops... we seem to have made a mistake, sorry!</p>279 <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>280 {% endblock %}281282It can be implemented by rendering the template on "500 Internal Server Error":283284.. code-block:: python285286 from flask import render_template287288 @app.errorhandler(500)289 def internal_server_error(e):290 # note that we set the 500 status explicitly291 return render_template('500.html'), 500292293294When using the :doc:`/patterns/appfactories`:295296.. code-block:: python297298299 from flask import Flask, render_template300301 def internal_server_error(e):302 return render_template('500.html'), 500303304 def create_app():305 app = Flask(__name__)306 app.register_error_handler(500, internal_server_error)307 return app308309310When using :doc:`/blueprints`:311312.. code-block:: python313314 from flask import Blueprint315316 blog = Blueprint('blog', __name__)317318 # as a decorator319 @blog.errorhandler(500)320 def internal_server_error(e):321 return render_template('500.html'), 500322323 # or with register_error_handler324 blog.register_error_handler(500, internal_server_error)325326327328In 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:337338.. code-block:: python339340 from flask import jsonify, render_template341342 # at the application level343 # not the blueprint level344 @app.errorhandler(404)345 def page_not_found(e):346 # if a request is in our blog URL space347 if request.path.startswith('/blog/'):348 # we return a custom blog 404 page349 return render_template("blog/404.html"), 404350 else:351 # otherwise we return our generic site-wide 404 page352 return render_template("404.html"), 404353354355 @app.errorhandler(405)356 def method_not_allowed(e):357 # if a request has the wrong method to our API358 if request.path.startswith('/api/'):359 # we return a json saying so360 return jsonify(message="Method Not Allowed"), 405361 else:362 # otherwise we return a generic site-wide 405 page363 return render_template("405.html"), 405364365366367More 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 builtin375exceptions are not expressive enough for APIs and that the content type of376:mimetype:`text/html` they are emitting is not very useful for API consumers.377378Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON379responses to API errors. :func:`~flask.abort` is called380with a ``description`` parameter. The errorhandler will381use that as the JSON error message, and set the status code to 404.382383.. code-block:: python384385 from flask import abort, jsonify386387 @app.errorhandler(404)388 def resource_not_found(e):389 return jsonify(error=str(e)), 404390391 @app.route("/cheese")392 def get_one_cheese():393 resource = get_resource()394395 if resource is None:396 abort(404, description="Resource not found")397398 return jsonify(resource)399400401402We 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,404a status code for the error and some optional payload to give more context405for the error.406407This is a simple example:408409.. code-block:: python410411 from flask import jsonify, request412413 class InvalidAPIUsage(Exception):414 status_code = 400415416 def __init__(self, message, status_code=None, payload=None):417 super().__init__()418 self.message = message419 if status_code is not None:420 self.status_code = status_code421 self.payload = payload422423 def to_dict(self):424 rv = dict(self.payload or ())425 rv['message'] = self.message426 return rv427428 @app.errorhandler(InvalidAPIUsage)429 def invalid_api_usage(e):430 return jsonify(e.to_dict())431432 # an API app route for getting user information433 # a correct request might be /api/user?user_id=420434 @app.route("/api/user")435 def user_api(user_id):436 user_id = request.arg.get("user_id")437 if not user_id:438 raise InvalidAPIUsage("No user id provided!")439440 user = get_user(user_id=user_id)441 if not user:442 raise InvalidAPIUsage("No such user!", status_code=404)443444 return jsonify(user.to_dict())445446447A view can now raise that exception with an error message. Additionally448some extra payload can be provided as a dictionary through the `payload`449parameter.450451452Generic Exception Handlers453``````````````````````````454455It is possible to register error handlers for very generic base classes
24 unmodified lines
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 status
18 unmodified lines
512register handlers for both ``HTTPException`` and ``Exception``, the513``Exception`` handler will not handle ``HTTPException`` subclasses514because it the ``HTTPException`` handler is more specific.515199Unhandled Exceptions200````````````````````516202When there is no error handler registered for an exception, a 500203Internal Server Error will be returned instead. See204:meth:`flask.Flask.handle_exception` for information about this205behavior.517Generic Error Pages518-------------------519207If there is an error handler registered for ``InternalServerError``,208this will be invoked. As of Flask 1.1.0, this error handler will always209be passed an instance of ``InternalServerError``, not the original210unhandled error. The original error is available as ``e.original_exception``.211Until Werkzeug 1.0.0, this attribute will only exist during unhandled212errors, use ``getattr`` to get access it for compatibility.520If we pass in the exception into a template as below:521522.. code-block:: python523216 @app.errorhandler(InternalServerError)217 def handle_500(e):218 original = getattr(e, "original_exception", None)524 from werkzeug.exceptions import HTTPException525220 if original is None:221 # direct 500 error, such as abort(500)222 return render_template("500.html"), 500526 @app.errorhandler(HTTPException)527 def handle_exception(e):528 return render_template("exception.html", e=e), e.code529224 # wrapped unhandled error225 return render_template("500_unhandled.html", e=original), 500530531228Logging229-------532.. sourcecode:: html+jinja533231See :doc:`/logging` for information on how to log exceptions, such as by232emailing them to admins.534 {% 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 Errors236============================545````````````````````````````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.551552Logging553-------554555See :doc:`/logging` for information on how to log exceptions, such as by556emailing them to admins.557558559560When in Doubt, Run Manually561---------------------------562563Having problems getting your application configured for production? If you
43 unmodified lines
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/>`_.