Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

524 lines · 18.0 KiB

Last changed by

Merge pull request #3894 from pallets/update-werkzeugDavid Lordbefore adoption9f7ac04

History of this file

Take it

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

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 1–2why, one step back
1Handling Application Errors
2===========================

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 3why, one step back
3

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 4–7why, one step back
4Applications fail, servers fail. Sooner or later you will see an exception
5in 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 server

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 8–18why, one step back
8errors:
910- the client terminated the request early and the application was still11 reading from the incoming data12- the database server was overloaded and could not handle the query13- a filesystem is full14- a harddrive crashed15- a backend server overloaded16- a programming error in a library you are using17- network connection of the server to another system failed18

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 19–20why, one step back
19And that's just a small sample of issues you could be facing. So how do we
20deal with that sort of problem? By default if your application runs in

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 21–22why, one step back
21production mode, and an exception is raised Flask will display a very simple
22page for you and log the exception to the :attr:`~flask.Flask.logger`.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 23–24why, one step back
23
24But there is more you can do, and we will cover some better setups to deal

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 25why, one step back
25with errors including custom exceptions and 3rd party tools.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 26–27why, one step back
26
27

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 28why, one step back
28.. _error-logging-tools:

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 29why, one step back
29

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 30–31why, one step back
30Error Logging Tools
31-------------------

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 32why, one step back
32

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 33–36why, one step back
33Sending error mails, even if just for critical ones, can become
34overwhelming 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's

Correct Sentry advertisement (not Free Software) (#3758)girstbefore adoptionde464c0

line 37why, one step back
37available as a source-available project `on GitHub

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 38–42why, one step back
38<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version
39<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.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 43why, one step back
43

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 44–45why, one step back
44To use Sentry you need to install the ``sentry-sdk`` client with extra
45``flask`` dependencies.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 46why, one step back
46

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 47why, one step back
47.. code-block:: text

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 48why, one step back
48

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 49why, one step back
49 $ pip install sentry-sdk[flask]

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 50why, one step back
50

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 51why, one step back
51And then add this to your Flask app:

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 52why, one step back
52

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 53why, one step back
53.. code-block:: python

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 54why, one step back
54

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 55–56why, one step back
55 import sentry_sdk
56 from sentry_sdk.integrations.flask import FlaskIntegration

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 57why, one step back
57

aesthetic: add a space after a comma (#3771)sblondonbefore adoption7e312c4

line 58why, one step back
58 sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 59why, one step back
59

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 60–61why, one step back
60The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you
61get from your Sentry installation.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 62why, one step back
62

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 63–72why, one step back
63After installation, failures leading to an Internal Server Error
64are 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>`__

Merge branch '1.1.x'David Lordbefore adoption15a49e7

line 73why, one step back
73- `Flask-specific documentation <https://docs.sentry.io/platforms/python/guides/flask/>`__

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 74–142why, one step back
74
7576Error 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````````142

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 143–144why, one step back
143When building a Flask application you *will* run into exceptions. If some part
144of your code breaks while handling a request (and you have no error handlers

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 145why, one step back
145registered), a "500 Internal Server Error"

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 146why, one step back
146(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 147–149why, one step back
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"

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 150–152why, one step back
150(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all
151subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by152default in Flask.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 153why, one step back
153

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 154why, one step back
154Flask gives you to the ability to raise any HTTP exception registered by

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 155–157why, one step back
155Werkzeug. However, the default HTTP exceptions return simple exception
156pages. You might want to show custom error pages to the user when an error occurs.157This can be done by registering error handlers.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 158why, one step back
158

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 159–161why, one step back
159When 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 a

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 162–176why, one step back
162generic message about their code, while other exceptions are converted to a
163generic "500 Internal Server Error".164165For example, if an instance of :exc:`ConnectionRefusedError` is raised,166and a handler is registered for :exc:`ConnectionError` and167:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`168handler is called with the exception instance to generate the response.169170Handlers registered on the blueprint take precedence over those registered171globally on the application, assuming a blueprint is handling the request that172raises the exception. However, the blueprint cannot handle 404 routing errors173because the 404 occurs at the routing level before the blueprint can be174determined.175176

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 177–178why, one step back
177Generic Exception Handlers
178``````````````````````````

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 179why, one step back
179

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 180–182why, one step back
180It is possible to register error handlers for very generic base classes
181such as ``HTTPException`` or even ``Exception``. However, be aware that182these will catch more than you might expect.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 183why, one step back
183

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 184–188why, one step back
184For example, an error handler for ``HTTPException`` might be useful for turning
185the 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.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 189–191why, one step back
189
190.. code-block:: python191

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 192–193why, one step back
192 from flask import json
193 from werkzeug.exceptions import HTTPException

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 194why, one step back
194

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 195–207why, one step back
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 response

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 208why, one step back
208

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 209–213why, one step back
209An error handler for ``Exception`` might seem useful for changing how
210all 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.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 214why, one step back
214

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 215–217why, one step back
215In most cases it will be safer to register handlers for more
216specific exceptions. Since ``HTTPException`` instances are valid WSGI217responses, you could also pass them through directly.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 218–220why, one step back
218
219.. code-block:: python220

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 221why, one step back
221 from werkzeug.exceptions import HTTPException

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 222why, one step back
222

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 223–227why, one step back
223 @app.errorhandler(Exception)
224 def handle_exception(e):225 # pass through HTTP errors226 if isinstance(e, HTTPException):227 return e

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 228why, one step back
228

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 229–230why, one step back
229 # now you're handling non-HTTP exceptions only
230 return render_template("500_generic.html", e=e), 500

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 231why, one step back
231

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 232–235why, one step back
232Error handlers still respect the exception class hierarchy. If you
233register handlers for both ``HTTPException`` and ``Exception``, the234``Exception`` handler will not handle ``HTTPException`` subclasses235because it the ``HTTPException`` handler is more specific.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

lines 236–237why, one step back
236
237

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 238–239why, one step back
238Unhandled Exceptions
239````````````````````

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 240why, one step back
240

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 241–244why, one step back
241When there is no error handler registered for an exception, a 500
242Internal Server Error will be returned instead. See243:meth:`flask.Flask.handle_exception` for information about this244behavior.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 245–248why, one step back
245
246If 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 original

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 249–251why, one step back
249unhandled error.
250251The original error is available as ``e.original_exception``.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 252why, one step back
252

Merge pull request #3894 from pallets/update-werkzeugDavid Lordbefore adoption9f7ac04

lines 253–256why, one step back
253An error handler for "500 Internal Server Error" will be passed uncaught
254exceptions in addition to explicit 500 errors. In debug mode, a handler255for "500 Internal Server Error" will not be used. Instead, the256interactive debugger will be shown.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 257–258why, one step back
257
258

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 259–260why, one step back
259Custom Error Pages
260------------------

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 261why, one step back
261

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 262–267why, one step back
262Sometimes when building a Flask application, you might want to raise a
263:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that264something is wrong with the request. Fortunately, Flask comes with a handy265:func:`~flask.abort` function that aborts a request with a HTTP error from266werkzeug as desired. It will also provide a plain black and white error page267for you with a basic description, but nothing fancy.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 268why, one step back
268

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 269–270why, one step back
269Depending on the error code it is less or more likely for the user to
270actually see such an error.

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 271why, one step back
271

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 272–275why, one step back
272Consider the code below, we might have a user profile route, and if the user
273fails to pass a username we can raise a "400 Bad Request". If the user passes a274username and we can't find it, we raise a "404 Not Found".275

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 276–277why, one step back
276.. code-block:: python
277

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 278why, one step back
278 from flask import abort, render_template, request

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 279why, one step back
279

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 280–287why, one step back
280 # a username needs to be supplied in the query args
281 # a successful request would be like /profile?username=jack282 @app.route("/profile")283 def user_profile():284 username = request.arg.get("username")285 # if a username isn't supplied in the request, return a 400 bad request286 if username is None:287 abort(400)

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 288why, one step back
288

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 289–292why, one step back
289 user = get_user(username=username)
290 # if a user can't be found by their username, return 404 not found291 if user is None:292 abort(404)

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 293why, one step back
293

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 294why, one step back
294 return render_template("profile.html", user=user)

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 295why, one step back
295

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 296why, one step back
296Here is another example implementation for a "404 Page Not Found" exception:

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 297why, one step back
297

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 298why, one step back
298.. code-block:: python

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 299why, one step back
299

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 300why, one step back
300 from flask import render_template

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 301why, one step back
301

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 302–305why, one step back
302 @app.errorhandler(404)
303 def page_not_found(e):304 # note that we set the 404 status explicitly305 return render_template('404.html'), 404

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 306why, one step back
306

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 307why, one step back
307When using :doc:`/patterns/appfactories`:

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 308why, one step back
308

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 309–336why, one step back
309.. code-block:: python
310311 from flask import Flask, render_template312313 def page_not_found(e):314 return render_template('404.html'), 404315316 def create_app(config_filename):317 app = Flask(__name__)318 app.register_error_handler(404, page_not_found)319 return app320321An example template might be this:322323.. code-block:: html+jinja324325 {% extends "layout.html" %}326 {% block title %}Page Not Found{% endblock %}327 {% block body %}328 <h1>Page Not Found</h1>329 <p>What you were looking for is just not there.330 <p><a href="{{ url_for('index') }}">go somewhere nice</a>331 {% endblock %}332333334Further Examples335````````````````336

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 337–338why, one step back
337The above examples wouldn't actually be an improvement on the default
338exception pages. We can create a custom 500.html template like this:

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 339why, one step back
339

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 340why, one step back
340.. code-block:: html+jinja

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 341–360why, one step back
341
342 {% extends "layout.html" %}343 {% block title %}Internal Server Error{% endblock %}344 {% block body %}345 <h1>Internal Server Error</h1>346 <p>Oops... we seem to have made a mistake, sorry!</p>347 <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>348 {% endblock %}349350It can be implemented by rendering the template on "500 Internal Server Error":351352.. code-block:: python353354 from flask import render_template355356 @app.errorhandler(500)357 def internal_server_error(e):358 # note that we set the 500 status explicitly359 return render_template('500.html'), 500360

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 361why, one step back
361When using :doc:`/patterns/appfactories`:

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 362–391why, one step back
362
363.. code-block:: python364365 from flask import Flask, render_template366367 def internal_server_error(e):368 return render_template('500.html'), 500369370 def create_app():371 app = Flask(__name__)372 app.register_error_handler(500, internal_server_error)373 return app374375When using :doc:`/blueprints`:376377.. code-block:: python378379 from flask import Blueprint380381 blog = Blueprint('blog', __name__)382383 # as a decorator384 @blog.errorhandler(500)385 def internal_server_error(e):386 return render_template('500.html'), 500387388 # or with register_error_handler389 blog.register_error_handler(500, internal_server_error)390391

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 392–393why, one step back
392Blueprint Error Handlers
393------------------------

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 394why, one step back
394

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 395–399why, one step back
395In :doc:`/blueprints`, most error handlers will work as expected.
396However, there is a caveat concerning handlers for 404 and 405397exceptions. These error handlers are only invoked from an appropriate398``raise`` statement or a call to ``abort`` in another of the blueprint's399view functions; they are not invoked by, e.g., an invalid URL access.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 400why, one step back
400

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 401–407why, one step back
401This is because the blueprint does not "own" a certain URL space, so
402the application instance has no way of knowing which blueprint error403handler it should run if given an invalid URL. If you would like to404execute different handling strategies for these errors based on URL405prefixes, they may be defined at the application level using the406``request`` proxy object.407

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 408–434why, one step back
408.. code-block:: python
409410 from flask import jsonify, render_template411412 # at the application level413 # not the blueprint level414 @app.errorhandler(404)415 def page_not_found(e):416 # if a request is in our blog URL space417 if request.path.startswith('/blog/'):418 # we return a custom blog 404 page419 return render_template("blog/404.html"), 404420 else:421 # otherwise we return our generic site-wide 404 page422 return render_template("404.html"), 404423424 @app.errorhandler(405)425 def method_not_allowed(e):426 # if a request has the wrong method to our API427 if request.path.startswith('/api/'):428 # we return a json saying so429 return jsonify(message="Method Not Allowed"), 405430 else:431 # otherwise we return a generic site-wide 405 page432 return render_template("405.html"), 405433434

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 435–436why, one step back
435Returning API Errors as JSON
436----------------------------

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 437why, one step back
437

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 438why, one step back
438When building APIs in Flask, some developers realise that the built-in

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 439–443why, one step back
439exceptions are not expressive enough for APIs and that the content type of
440:mimetype:`text/html` they are emitting is not very useful for API consumers.441442Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON443responses to API errors. :func:`~flask.abort` is called

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 444why, one step back
444with a ``description`` parameter. The error handler will

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 445–463why, one step back
445use that as the JSON error message, and set the status code to 404.
446447.. code-block:: python448449 from flask import abort, jsonify450451 @app.errorhandler(404)452 def resource_not_found(e):453 return jsonify(error=str(e)), 404454455 @app.route("/cheese")456 def get_one_cheese():457 resource = get_resource()458459 if resource is None:460 abort(404, description="Resource not found")461462 return jsonify(resource)463

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 464–465why, one step back
464We can also create custom exception classes. For instance, we can
465introduce a new custom exception for an API that can take a proper human readable message,

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 466–507why, one step back
466a status code for the error and some optional payload to give more context
467for the error.468469This is a simple example:470471.. code-block:: python472473 from flask import jsonify, request474475 class InvalidAPIUsage(Exception):476 status_code = 400477478 def __init__(self, message, status_code=None, payload=None):479 super().__init__()480 self.message = message481 if status_code is not None:482 self.status_code = status_code483 self.payload = payload484485 def to_dict(self):486 rv = dict(self.payload or ())487 rv['message'] = self.message488 return rv489490 @app.errorhandler(InvalidAPIUsage)491 def invalid_api_usage(e):492 return jsonify(e.to_dict())493494 # an API app route for getting user information495 # a correct request might be /api/user?user_id=420496 @app.route("/api/user")497 def user_api(user_id):498 user_id = request.arg.get("user_id")499 if not user_id:500 raise InvalidAPIUsage("No user id provided!")501502 user = get_user(user_id=user_id)503 if not user:504 raise InvalidAPIUsage("No such user!", status_code=404)505506 return jsonify(user.to_dict())507

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

line 508why, one step back
508A view can now raise that exception with an error message. Additionally

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 509–514why, one step back
509some extra payload can be provided as a dictionary through the `payload`
510parameter.511512513Logging514-------

Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1

line 515why, one step back
515

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 516–517why, one step back
516See :doc:`/logging` for information about how to log exceptions, such as
517by emailing them to admins.

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

lines 518–519why, one step back
518
519

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 520–521why, one step back
520Debugging
521---------

Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3

line 522why, one step back
522

Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8

lines 523–524why, one step back
523See :doc:`/debugging` for information about how to debug errors in
524development and production.