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
Provenance
- Commit
21c3df3- Tree
9ca1863- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
165f059- Parent 2
59b0b85
5 files changed+460 added−288 removed
deleted:docs/patterns/apierrors.rst-63 removed
1-Implementing API Exceptions2-===========================3-4-It's very common to implement RESTful APIs on top of Flask. One of the5-first things that developers run into is the realization that the builtin6-exceptions 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.8-9-The better solution than using ``abort`` to signal errors for invalid API10-usage is to implement your own exception type and install an error handler11-for it that produces the errors in the format the user is expecting.12-13-Simple Exception Class14-----------------------15-16-The basic idea is to introduce a new exception that can take a proper17-human readable message, a status code for the error and some optional18-payload to give more context for the error.19-20-This is a simple example::21-22- from flask import jsonify23-24- class InvalidUsage(Exception):25- status_code = 40026-27- 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 = payload33-34- def to_dict(self):35- rv = dict(self.payload or ())36- rv['message'] = self.message37- return rv38-39-A view can now raise that exception with an error message. Additionally40-some extra payload can be provided as a dictionary through the `payload`41-parameter.42-43-Registering an Error Handler44-----------------------------45-46-At that point views can raise that error, but it would immediately result47-in an internal server error. The reason for this is that there is no48-handler registered for this error class. That however is easy to add::49-50- @app.errorhandler(InvalidUsage)51- def handle_invalid_usage(error):52- response = jsonify(error.to_dict())53- response.status_code = error.status_code54- return response55-56-Usage in Views57---------------58-59-Here is how a view can use that functionality::60-61- @app.route('/foo')62- def get_foo():63- raise InvalidUsage('This view is gone', status_code=410)deleted:docs/patterns/errorpages.rst-123 removed
1-Custom Error Pages2-==================3-4-Flask comes with a handy :func:`~flask.abort` function that aborts a5-request with an HTTP error code early. It will also provide a plain black6-and white error page for you with a basic description, but nothing fancy.7-8-Depending on the error code it is less or more likely for the user to9-actually see such an error.10-11-Common Error Codes12-------------------13-14-The following error codes are some that are often displayed to the user,15-even if the application behaves correctly:16-17-*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.23-24-*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.28-29-*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.37-38-*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`).43-44-45-Error Handlers46---------------47-48-An error handler is a function that returns a response when a type of error is49-raised, similar to how a view is a function that returns a response when a50-request URL is matched. It is passed the instance of the error being handled,51-which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error52-handler for "500 Internal Server Error" will be passed uncaught exceptions in53-addition to explicit 500 errors.54-55-An error handler is registered with the :meth:`~flask.Flask.errorhandler`56-decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler57-can be registered for a status code, like 404, or for an exception class.58-59-The status code of the response will not be set to the handler's code. Make60-sure to provide the appropriate HTTP status code when returning a response from61-a handler.62-63-A handler for "500 Internal Server Error" will not be used when running in64-debug mode. Instead, the interactive debugger will be shown.65-66-Here is an example implementation for a "404 Page Not Found" exception::67-68- from flask import render_template69-70- @app.errorhandler(404)71- def page_not_found(e):72- # note that we set the 404 status explicitly73- return render_template('404.html'), 40474-75-When using the :doc:`appfactories`::76-77- from flask import Flask, render_template78-79- def page_not_found(e):80- return render_template('404.html'), 40481-82- def create_app(config_filename):83- app = Flask(__name__)84- app.register_error_handler(404, page_not_found)85- return app86-87-An example template might be this:88-89-.. sourcecode:: html+jinja90-91- {% 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 %}98-99-100-Returning API errors as JSON101-----------------------------102-103-When using Flask for web APIs, you can use the same techniques as above104-to return JSON responses to API errors. :func:`~flask.abort` is called105-with a ``description`` parameter. The :meth:`~flask.errorhandler` will106-use that as the JSON error message, and set the status code to 404.107-108-.. code-block:: python109-110- from flask import abort, jsonify111-112- @app.errorhandler(404)113- def resource_not_found(e):114- return jsonify(error=str(e)), 404115-116- @app.route("/cheese")117- def get_one_cheese():118- resource = get_resource()119-120- if resource is None:121- abort(404, description="Resource not found")122-123- return jsonify(resource)modified:docs/patterns/index.rst-2 removed
16 unmodified lines17 18 packages19 appfactories20 appdispatch21- apierrors21 urlprocessors22 distribute23 fabric24 sqlite34 unmodified lines29 wtforms30 templateinheritance31 flashing32 jquery34- errorpages33 lazyloading34 mongoengine35 favicon36 streaming6 unmodified linesmodified:docs/blueprints.rst+1 added-1 removed
271 unmodified lines272 return jsonify_error(ex)273 else:274 return ex275 276-More information on error handling see :doc:`/patterns/errorpages`.276+See :doc:`/errorhandling`.modified:docs/errorhandling.rst+459 added-99 removed
1-Application Errors2-==================1+Handling Application Errors2+===========================3 4 .. versionadded:: 0.35 6 Applications fail, servers fail. Sooner or later you will see an exception12 unmodified lines19 - network connection of the server to another system failed20 21 And that's just a small sample of issues you could be facing. So how do we22 deal with that sort of problem? By default if your application runs in23-production mode, Flask will display a very simple page for you and log the24-exception to the :attr:`~flask.Flask.logger`.23+production mode, and an exception is raised Flask will display a very simple24+page for you and log the exception to the :attr:`~flask.Flask.logger`.25 26 But there is more you can do, and we will cover some better setups to deal27-with errors.27+with errors including custom exceptions and 3rd party tools.28 29-Error Logging Tools30--------------------29 32-Sending error mails, even if just for critical ones, can become33-overwhelming if enough users are hitting the error and log files are34-typically never looked at. This is why we recommend using `Sentry35-<https://sentry.io/>`_ for dealing with application errors. It's36-available 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. Sentry39-aggregates duplicate errors, captures the full stack trace and local40-variables for debugging, and sends you mails based on new errors or41-frequency thresholds.30+.. _common-error-codes:31 43-To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::32+Common Error Codes33+``````````````````34 45- $ pip install sentry-sdk[flask]35+The following error codes are some that are often displayed to the user,36+even if the application behaves correctly:37 47-And 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.42 49- 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.47 52- 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.54 54-The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get55-from 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.63 57-After installation, failures leading to an Internal Server Error58-are automatically reported to Sentry and from there you can59-receive 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.68 61-Follow-up reads:69 63-* 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/>`_.70 71+Default Error Handling72+``````````````````````73 70-Error handlers71---------------74+When building a Flask application you *will* run into exceptions. If some part75+of your code breaks while handling a request (and you have no error handlers76+registered) an "500 Internal Server Error"77+(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.78+Similarly, 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 an80+unallowed request method a "405 Method Not Allowed"81+(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all82+subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by83+default in Flask.84 73-You might want to show custom error pages to the user when an error occurs.74-This can be done by registering error handlers.85+Flask gives you to the ability to raise any HTTP exception registered by86+werkzeug. However, as the default HTTP exceptions return simple exception87+pages, Flask also offers the opportunity to customise these HTTP exceptions via88+custom error handlers as well as to add exception handlers for builtin and89+custom exceptions.90 91+When an exception is caught by Flask while handling a request, it is first92+looked up by code. If no handler is registered for the code, it is looked up93+by its class hierarchy; the most specific handler is chosen. If no handler is94+registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a95+generic message about their code, while other exceptions are converted to a96+generic "500 Internal Server Error".97+98+For example, if an instance of :exc:`ConnectionRefusedError` is raised,99+and a handler is registered for :exc:`ConnectionError` and100+:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`101+handler is called with the exception instance to generate the response.102+103+Handlers registered on the blueprint take precedence over those registered104+globally on the application, assuming a blueprint is handling the request that105+raises the exception. However, the blueprint cannot handle 404 routing errors106+because the 404 occurs at the routing level before the blueprint can be107+determined.108+109+110+111+.. _handling-errors:112+113+Handling Errors114+```````````````115+116+Sometimes when building a Flask application, you might want to raise a117+:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that118+something is wrong with the request. Fortunately, Flask comes with a handy119+:func:`~flask.abort` function that aborts a request with a HTTP error from120+werkzeug as desired.121+122+Consider the code below, we might have a user profile route, but if the user123+fails to pass a username we raise a "400 Bad Request" and if the user passes a124+username but we can't find it, we raise a "404 Not Found".125+126+.. code-block:: python127+128+ from flask import abort, render_template, request129+130+ # 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)138+139+ 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)143+144+ return render_template("profile.html", user=user)145+146+147+148+.. _custom-error-handlers:149+150+Custom error handlers151+`````````````````````152+153+The default :exc:`~werkzeug.exceptions.HTTPException` returns a black and white154+error page with a basic description, but nothing fancy. Considering155+these errors *will* be thrown during the lifetime of your application, it is156+highly advisable to customise these exceptions to improve the user experience157+of your site. This can be done by registering error handlers.158+159 An error handler is a normal view function that returns a response, but instead160 of being registered for a route, it is registered for an exception or HTTP161 status code that would be raised while trying to handle a request.162 80-Registering81-```````````163+It is passed the instance of the error being handled, which is most164+likely an integer that represents a :exc:`~werkzeug.exceptions.HTTPException`165+status code. For example 500 (an "Internal Server Error") which maps to166+:exc:`~werkzeug.exceptions.InternalServerError`.167 83-Register handlers by decorating a function with84-:meth:`~flask.Flask.errorhandler`. Or use85-:meth:`~flask.Flask.register_error_handler` to register the function later.86-Remember to set the error code when returning the response. ::168+It is registered with the :meth:`~flask.Flask.errorhandler`169+decorator or the :meth:`~flask.Flask.register_error_handler` to register170+the function later. A handler can be registered for a status code,171+like 404 or 500, or for an built-in exception class, like KeyError,172+or a custom exception class that inherits from Exception or its subclasses.173 88- @app.errorhandler(werkzeug.exceptions.BadRequest)89- def handle_bad_request(e):90- return 'bad request!', 400174+The status code of the response will not be set to the handler's code. Make175+sure to provide the appropriate HTTP status code when returning a response from176+a handler or a 200 OK HTTP code will be sent instead.177 178+.. code-block:: python179+180+ from werkzeug.exceptions import InternalServerError181+182+ # 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!', 500189+190+ # 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.code195+196 # or, without the decorator93- app.register_error_handler(400, handle_bad_request)197+ app.register_error_handler(500, handle_internal_server_error)198 95-:exc:`werkzeug.exceptions.HTTPException` subclasses like96-:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable97-when registering handlers. (``BadRequest.code == 400``)199+ # similarly with a werkzeug exception200+ app.register_error_handler(InternalServerError, handle_internal_server_error)201 202+203+204+A handler for "500 Internal Server Error" will not be used when running in205+debug mode. Instead, the interactive debugger will be shown.206+207+If there is an error handler registered for ``InternalServerError``,208+this will be invoked. As of Flask 1.1.0, this error handler will always209+be passed an instance of ``InternalServerError``, not the original210+unhandled error. The original error is available as ``e.original_exception``.211+Until Werkzeug 1.0.0, this attribute will only exist during unhandled212+errors, use ``getattr`` to get access it for compatibility.213+214+.. code-block:: python215+216+ @app.errorhandler(InternalServerError)217+ def handle_500(e):218+ original = getattr(e, "original_exception", None)219+220+ if original is None:221+ # direct 500 error, such as abort(500)222+ return render_template("500.html"), 500223+224+ # wrapped unhandled error225+ return render_template("500_unhandled.html", e=original), 500226+227+228+229+Registering Custom Exceptions230+-----------------------------231+232+You can create your own custom exceptions by subclassing233+:exc:`werkzeug.exceptions.HTTPException`. As shown above, integer HTTP codes234+are interchangable when registering handlers. (``BadRequest.code == 400``)235+236 Non-standard HTTP codes cannot be registered by code because they are not known237 by Werkzeug. Instead, define a subclass of238 :class:`~werkzeug.exceptions.HTTPException` with the appropriate code and102-register and raise that exception class. ::239+register and raise that exception class:240 241+.. code-block:: python242+243 class InsufficientStorage(werkzeug.exceptions.HTTPException):244 code = 507245 description = 'Not enough storage space.'246 247+ def handle_507(e):248+ return 'Not enough storage space!', 507249+250 app.register_error_handler(InsufficientStorage, handle_507)251 252+ # during an request253 raise InsufficientStorage()254 112-Handlers can be registered for any exception class, not just113-:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status114-codes. Handlers can be registered for a specific class, or for all subclasses115-of a parent class.255+Handlers can be registered for any exception class that inherits from Exception.256 117-Handling118-````````257 120-When an exception is caught by Flask while handling a request, it is first121-looked up by code. If no handler is registered for the code, it is looked up122-by its class hierarchy; the most specific handler is chosen. If no handler is123-registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a124-generic message about their code, while other exceptions are converted to a125-generic 500 Internal Server Error.258+Unhandled Exceptions259+--------------------260 127-For example, if an instance of :exc:`ConnectionRefusedError` is raised,128-and a handler is registered for :exc:`ConnectionError` and129-:exc:`ConnectionRefusedError`,130-the more specific :exc:`ConnectionRefusedError` handler is called with the131-exception instance to generate the response.261+If an exception is raised in the code while Flask is handling a request and262+there is no error handler registered for that exception, a "500 Internal Server263+Error" will be returned instead. See :meth:`flask.Flask.handle_exception` for264+information about this behavior.265 133-Handlers registered on the blueprint take precedence over those registered134-globally on the application, assuming a blueprint is handling the request that135-raises the exception. However, the blueprint cannot handle 404 routing errors136-because the 404 occurs at the routing level before the blueprint can be137-determined.266+Custom error pages267+------------------268 269+The above examples wouldn't actually be an improvement on the default270+exception pages. We can create a custom 500.html template like this:271 272+.. sourcecode:: html+jinja273+274+ {% 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 %}281+282+It can be implemented by rendering the template on "500 Internal Server Error":283+284+.. code-block:: python285+286+ from flask import render_template287+288+ @app.errorhandler(500)289+ def internal_server_error(e):290+ # note that we set the 500 status explicitly291+ return render_template('500.html'), 500292+293+294+When using the :doc:`/patterns/appfactories`:295+296+.. code-block:: python297+298+299+ from flask import Flask, render_template300+301+ def internal_server_error(e):302+ return render_template('500.html'), 500303+304+ def create_app():305+ app = Flask(__name__)306+ app.register_error_handler(500, internal_server_error)307+ return app308+309+310+When using :doc:`/blueprints`:311+312+.. code-block:: python313+314+ from flask import Blueprint315+316+ blog = Blueprint('blog', __name__)317+318+ # as a decorator319+ @blog.errorhandler(500)320+ def internal_server_error(e):321+ return render_template('500.html'), 500322+323+ # or with register_error_handler324+ blog.register_error_handler(500, internal_server_error)325+326+327+328+In blueprints errorhandlers will simply work as expected; however, there is a caveat329+concerning handlers for 404 and 405 exceptions. These errorhandlers are only330+invoked from an appropriate ``raise`` statement or a call to ``abort`` in another331+of the blueprint's view functions; they are not invoked by, e.g., an invalid URL332+access. This is because the blueprint does not "own" a certain URL space, so333+the application instance has no way of knowing which blueprint error handler it334+should run if given an invalid URL. If you would like to execute different335+handling strategies for these errors based on URL prefixes, they may be defined336+at the application level using the ``request`` proxy object:337+338+.. code-block:: python339+340+ from flask import jsonify, render_template341+342+ # 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"), 404353+354+355+ @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"), 405364+365+366+367+More information on error handling with blueprint can be found in368+:doc:`/blueprints`.369+370+371+Returning API errors as JSON372+````````````````````````````373+374+When building APIs in Flask, some developers realise that the builtin375+exceptions 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.377+378+Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON379+responses to API errors. :func:`~flask.abort` is called380+with a ``description`` parameter. The errorhandler will381+use that as the JSON error message, and set the status code to 404.382+383+.. code-block:: python384+385+ from flask import abort, jsonify386+387+ @app.errorhandler(404)388+ def resource_not_found(e):389+ return jsonify(error=str(e)), 404390+391+ @app.route("/cheese")392+ def get_one_cheese():393+ resource = get_resource()394+395+ if resource is None:396+ abort(404, description="Resource not found")397+398+ return jsonify(resource)399+400+401+402+We can also create custom exception classes; for instance, for an API we can403+introduce a new custom exception that can take a proper human readable message,404+a status code for the error and some optional payload to give more context405+for the error.406+407+This is a simple example:408+409+.. code-block:: python410+411+ from flask import jsonify, request412+413+ class InvalidAPIUsage(Exception):414+ status_code = 400415+416+ 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 = payload422+423+ def to_dict(self):424+ rv = dict(self.payload or ())425+ rv['message'] = self.message426+ return rv427+428+ @app.errorhandler(InvalidAPIUsage)429+ def invalid_api_usage(e):430+ return jsonify(e.to_dict())431+432+ # 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!")439+440+ user = get_user(user_id=user_id)441+ if not user:442+ raise InvalidAPIUsage("No such user!", status_code=404)443+444+ return jsonify(user.to_dict())445+446+447+A view can now raise that exception with an error message. Additionally448+some extra payload can be provided as a dictionary through the `payload`449+parameter.450+451+452 Generic Exception Handlers453 ``````````````````````````454 455 It is possible to register error handlers for very generic base classes24 unmodified lines480 })481 response.content_type = "application/json"482 return response483 484+ # or using jsonify485+ @app.errorhandler(HTTPException)486+ def handle_exception(e):487+ return jsonify("code": e.code, "name": e.name, "description": e.description), e.code488 489+490 An error handler for ``Exception`` might seem useful for changing how491 all errors, even unhandled ones, are presented to the user. However,492 this is similar to doing ``except Exception:`` in Python, it will493 capture *all* otherwise unhandled errors, including all HTTP status18 unmodified lines512 register handlers for both ``HTTPException`` and ``Exception``, the513 ``Exception`` handler will not handle ``HTTPException`` subclasses514 because it the ``HTTPException`` handler is more specific.515 199-Unhandled Exceptions200-````````````````````516 202-When there is no error handler registered for an exception, a 500203-Internal Server Error will be returned instead. See204-:meth:`flask.Flask.handle_exception` for information about this205-behavior.517+Generic Error Pages518+-------------------519 207-If there is an error handler registered for ``InternalServerError``,208-this will be invoked. As of Flask 1.1.0, this error handler will always209-be passed an instance of ``InternalServerError``, not the original210-unhandled error. The original error is available as ``e.original_exception``.211-Until Werkzeug 1.0.0, this attribute will only exist during unhandled212-errors, use ``getattr`` to get access it for compatibility.520+If we pass in the exception into a template as below:521 522 .. code-block:: python523 216- @app.errorhandler(InternalServerError)217- def handle_500(e):218- original = getattr(e, "original_exception", None)524+ from werkzeug.exceptions import HTTPException525 220- 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.code529 224- # wrapped unhandled error225- return render_template("500_unhandled.html", e=original), 500530 531 228-Logging229--------532+.. sourcecode:: html+jinja533 231-See :doc:`/logging` for information on how to log exceptions, such as by232-emailing 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 %}541 542 543+544 Debugging Application Errors236-============================545+````````````````````````````546 547 For production applications, configure your application with logging and548 notifications as described in :doc:`/logging`. This section provides549 pointers when debugging deployment configuration and digging deeper with a550 full-featured Python debugger.551 552+Logging553+-------554 555+See :doc:`/logging` for information on how to log exceptions, such as by556+emailing them to admins.557+558+559+560 When in Doubt, Run Manually561 ---------------------------562 563 Having problems getting your application configured for production? If you43 unmodified lines607 608 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')611+612+613+.. _error-logging-tools:614+615+616+Error Logging Tools617+-------------------618+619+Sending error mails, even if just for critical ones, can become620+overwhelming if enough users are hitting the error and log files are621+typically never looked at. This is why we recommend using `Sentry622+<https://sentry.io/>`_ for dealing with application errors. It's623+available 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. Sentry626+aggregates duplicate errors, captures the full stack trace and local627+variables for debugging, and sends you mails based on new errors or628+frequency thresholds.629+630+To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::631+632+ $ pip install sentry-sdk[flask]633+634+And then add this to your Flask app::635+636+ import sentry_sdk637+ from sentry_sdk.integrations.flask import FlaskIntegration638+639+ sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])640+641+The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get642+from your Sentry installation.643+644+After installation, failures leading to an Internal Server Error645+are automatically reported to Sentry and from there you can646+receive error notifications.647+648+Follow-up reads:649+650+* 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/>`_.