errorhandling.rst
This file
Path
docs/errorhandling.rst
538 lines · 18.5 KiB
Last changed by
aesthetic: add a space after a comma (#3771)sblondonbefore adoption7e312c4
History of this fileTake it
The walk stopped after 200 commits: lines older than 4f3dbb3 point at it.
Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 1–2why, one step back1Handling Application Errors2===========================Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 3why, one step back3Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 4–7why, one step back4Applications fail, servers fail. Sooner or later you will see an exception5in production. Even if your code is 100% correct, you will still see6exceptions from time to time. Why? Because everything else involved will7fail. Here are some situations where perfectly fine code can lead to serverMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 8–18why, one step back8errors: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 failed18Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 19–20why, one step back19And that's just a small sample of issues you could be facing. So how do we20deal with that sort of problem? By default if your application runs inMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 21–22why, one step back21production mode, and an exception is raised Flask will display a very simple22page for you and log the exception to the :attr:`~flask.Flask.logger`.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 23–24why, one step back2324But there is more you can do, and we will cover some better setups to dealMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 25why, one step back25with errors including custom exceptions and 3rd party tools.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 26–27why, one step back2627Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 28why, one step back28.. _error-logging-tools:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 29why, one step back29Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 30–31why, one step back30Error Logging Tools31-------------------Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 32why, one step back32Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 33–36why, one step back33Sending error mails, even if just for critical ones, can become34overwhelming if enough users are hitting the error and log files are35typically never looked at. This is why we recommend using `Sentry36<https://sentry.io/>`_ for dealing with application errors. It'sCorrect Sentry advertisement (not Free Software) (#3758)girstbefore adoptionde464c0
line 37why, one step back37available as a source-available project `on GitHubMerge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 38–42why, one step back38<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version39<https://sentry.io/signup/>`_ which you can try for free. Sentry40aggregates duplicate errors, captures the full stack trace and local41variables for debugging, and sends you mails based on new errors or42frequency thresholds.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 43why, one step back43Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 44–45why, one step back44To use Sentry you need to install the ``sentry-sdk`` client with extra45``flask`` dependencies.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 46why, one step back46Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 47why, one step back47.. code-block:: textMerge pull request #3175 from singingwolfboy/fix-rst-line-too-longDavid Baumgoldbefore adoption819368a
line 48why, one step back48Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 49why, one step back49 $ pip install sentry-sdk[flask]Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 50why, one step back50Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 51why, one step back51And then add this to your Flask app:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 52why, one step back52Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 53why, one step back53.. code-block:: pythonMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 54why, one step back54Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 55–56why, one step back55 import sentry_sdk56 from sentry_sdk.integrations.flask import FlaskIntegrationMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 57why, one step back57aesthetic: add a space after a comma (#3771)sblondonbefore adoption7e312c4
line 58why, one step back58 sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 59why, one step back59Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 60–61why, one step back60The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you61get from your Sentry installation.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 62why, one step back62Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 63–142why, one step back63After installation, failures leading to an Internal Server Error64are automatically reported to Sentry and from there you can65receive error notifications.6667See also:6869- Sentry also supports catching errors from a worker queue70 (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs71 <https://docs.sentry.io/platforms/python/>`__ for more information.72- `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`__73- `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`__747576Error Handlers77--------------7879When an error occurs in Flask, an appropriate `HTTP status code80<https://developer.mozilla.org/en-US/docs/Web/HTTP/Status>`__ will be81returned. 400-499 indicate errors with the client's request data, or82about the data requested. 500-599 indicate errors with the server or83application itself.8485You might want to show custom error pages to the user when an error occurs.86This can be done by registering error handlers.8788An error handler is a function that returns a response when a type of error is89raised, similar to how a view is a function that returns a response when a90request URL is matched. It is passed the instance of the error being handled,91which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.9293The status code of the response will not be set to the handler's code. Make94sure to provide the appropriate HTTP status code when returning a response from95a handler.969798Registering99```````````100101Register handlers by decorating a function with102:meth:`~flask.Flask.errorhandler`. Or use103:meth:`~flask.Flask.register_error_handler` to register the function later.104Remember to set the error code when returning the response.105106.. code-block:: python107108 @app.errorhandler(werkzeug.exceptions.BadRequest)109 def handle_bad_request(e):110 return 'bad request!', 400111112 # or, without the decorator113 app.register_error_handler(400, handle_bad_request)114115:exc:`werkzeug.exceptions.HTTPException` subclasses like116:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable117when registering handlers. (``BadRequest.code == 400``)118119Non-standard HTTP codes cannot be registered by code because they are not known120by Werkzeug. Instead, define a subclass of121:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and122register and raise that exception class.123124.. code-block:: python125126 class InsufficientStorage(werkzeug.exceptions.HTTPException):127 code = 507128 description = 'Not enough storage space.'129130 app.register_error_handler(InsufficientStorage, handle_507)131132 raise InsufficientStorage()133134Handlers can be registered for any exception class, not just135:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status136codes. Handlers can be registered for a specific class, or for all subclasses137of a parent class.138139140Handling141````````142Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 143–144why, one step back143When building a Flask application you *will* run into exceptions. If some part144of your code breaks while handling a request (and you have no error handlersMerge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 145why, one step back145registered), a "500 Internal Server Error"Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 146why, one step back146(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 147–149why, one step back147Similarly, "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 back150(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all151subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by152default in Flask.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 153why, one step back153Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 154why, one step back154Flask gives you to the ability to raise any HTTP exception registered byMerge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 155–157why, one step back155Werkzeug. However, the default HTTP exceptions return simple exception156pages. You might want to show custom error pages to the user when an error occurs.157This can be done by registering error handlers.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 158why, one step back158Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 159–161why, one step back159When 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 aMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 162–176why, one step back162generic message about their code, while other exceptions are converted to a163generic "500 Internal Server Error".164165For example, if an instance of :exc:`ConnectionRefusedError` is raised,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.175176Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 177–178why, one step back177Generic Exception Handlers178``````````````````````````Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 179why, one step back179Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 180–182why, one step back180It is possible to register error handlers for very generic base classes181such as ``HTTPException`` or even ``Exception``. However, be aware that182these will catch more than you might expect.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 183why, one step back183Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 184–188why, one step back184For example, an error handler for ``HTTPException`` might be useful for turning185the default HTML errors pages into JSON. However, this186handler will trigger for things you don't cause directly, such as 404187and 405 errors during routing. Be sure to craft your handler carefully188so you don't lose information about the HTTP error.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 189–191why, one step back189190.. code-block:: python191Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 192–193why, one step back192 from flask import json193 from werkzeug.exceptions import HTTPExceptionMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 194why, one step back194Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 195–207why, one step back195 @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 responseMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 208why, one step back208Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 209–213why, one step back209An error handler for ``Exception`` might seem useful for changing how210all errors, even unhandled ones, are presented to the user. However,211this is similar to doing ``except Exception:`` in Python, it will212capture *all* otherwise unhandled errors, including all HTTP status213codes.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 214why, one step back214Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 215–217why, one step back215In most cases it will be safer to register handlers for more216specific exceptions. Since ``HTTPException`` instances are valid WSGI217responses, you could also pass them through directly.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 218–220why, one step back218219.. code-block:: python220Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 221why, one step back221 from werkzeug.exceptions import HTTPExceptionMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 222why, one step back222Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 223–227why, one step back223 @app.errorhandler(Exception)224 def handle_exception(e):225 # pass through HTTP errors226 if isinstance(e, HTTPException):227 return eMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 228why, one step back228Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 229–230why, one step back229 # now you're handling non-HTTP exceptions only230 return render_template("500_generic.html", e=e), 500Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 231why, one step back231Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 232–235why, one step back232Error handlers still respect the exception class hierarchy. If you233register handlers for both ``HTTPException`` and ``Exception``, the234``Exception`` handler will not handle ``HTTPException`` subclasses235because it the ``HTTPException`` handler is more specific.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 236–237why, one step back236237Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 238–239why, one step back238Unhandled Exceptions239````````````````````Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 240why, one step back240Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 241–244why, one step back241When there is no error handler registered for an exception, a 500242Internal Server Error will be returned instead. See243:meth:`flask.Flask.handle_exception` for information about this244behavior.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 245–248why, one step back245246If 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 originalMerge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 249–251why, one step back249unhandled error.250251The original error is available as ``e.original_exception``.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 252–267why, one step back252Until Werkzeug 1.0.0, this attribute will only exist during unhandled253errors, use ``getattr`` to get access it for compatibility.254255.. code-block:: python256257 @app.errorhandler(InternalServerError)258 def handle_500(e):259 original = getattr(e, "original_exception", None)260261 if original is None:262 # direct 500 error, such as abort(500)263 return render_template("500.html"), 500264265 # wrapped unhandled error266 return render_template("500_unhandled.html", e=original), 500267Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 268–270why, one step back268An error handler for "500 Internal Server Error" will be passed uncaught exceptions in269addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.270Instead, the interactive debugger will be shown.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 271–272why, one step back271272Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 273–274why, one step back273Custom Error Pages274------------------Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 275why, one step back275Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 276–281why, one step back276Sometimes when building a Flask application, you might want to raise a277:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that278something is wrong with the request. Fortunately, Flask comes with a handy279:func:`~flask.abort` function that aborts a request with a HTTP error from280werkzeug as desired. It will also provide a plain black and white error page281for you with a basic description, but nothing fancy.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 282why, one step back282Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 283–284why, one step back283Depending on the error code it is less or more likely for the user to284actually see such an error.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 285why, one step back285Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 286–289why, one step back286Consider the code below, we might have a user profile route, and if the user287fails to pass a username we can raise a "400 Bad Request". If the user passes a288username and we can't find it, we raise a "404 Not Found".289Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 290–291why, one step back290.. code-block:: python291Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 292why, one step back292 from flask import abort, render_template, requestMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 293why, one step back293Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 294–301why, one step back294 # a username needs to be supplied in the query args295 # a successful request would be like /profile?username=jack296 @app.route("/profile")297 def user_profile():298 username = request.arg.get("username")299 # if a username isn't supplied in the request, return a 400 bad request300 if username is None:301 abort(400)Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 302why, one step back302Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 303–306why, one step back303 user = get_user(username=username)304 # if a user can't be found by their username, return 404 not found305 if user is None:306 abort(404)Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 307why, one step back307Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 308why, one step back308 return render_template("profile.html", user=user)Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 309why, one step back309Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 310why, one step back310Here is another example implementation for a "404 Page Not Found" exception:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 311why, one step back311Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 312why, one step back312.. code-block:: pythonMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 313why, one step back313Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 314why, one step back314 from flask import render_templateMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 315why, one step back315Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 316–319why, one step back316 @app.errorhandler(404)317 def page_not_found(e):318 # note that we set the 404 status explicitly319 return render_template('404.html'), 404Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 320why, one step back320Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 321why, one step back321When using :doc:`/patterns/appfactories`:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 322why, one step back322Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 323–350why, one step back323.. code-block:: python324325 from flask import Flask, render_template326327 def page_not_found(e):328 return render_template('404.html'), 404329330 def create_app(config_filename):331 app = Flask(__name__)332 app.register_error_handler(404, page_not_found)333 return app334335An example template might be this:336337.. code-block:: html+jinja338339 {% extends "layout.html" %}340 {% block title %}Page Not Found{% endblock %}341 {% block body %}342 <h1>Page Not Found</h1>343 <p>What you were looking for is just not there.344 <p><a href="{{ url_for('index') }}">go somewhere nice</a>345 {% endblock %}346347348Further Examples349````````````````350Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 351–352why, one step back351The above examples wouldn't actually be an improvement on the default352exception pages. We can create a custom 500.html template like this:Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 353why, one step back353Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 354why, one step back354.. code-block:: html+jinjaMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 355–374why, one step back355356 {% extends "layout.html" %}357 {% block title %}Internal Server Error{% endblock %}358 {% block body %}359 <h1>Internal Server Error</h1>360 <p>Oops... we seem to have made a mistake, sorry!</p>361 <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a>362 {% endblock %}363364It can be implemented by rendering the template on "500 Internal Server Error":365366.. code-block:: python367368 from flask import render_template369370 @app.errorhandler(500)371 def internal_server_error(e):372 # note that we set the 500 status explicitly373 return render_template('500.html'), 500374Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 375why, one step back375When using :doc:`/patterns/appfactories`:Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 376–405why, one step back376377.. code-block:: python378379 from flask import Flask, render_template380381 def internal_server_error(e):382 return render_template('500.html'), 500383384 def create_app():385 app = Flask(__name__)386 app.register_error_handler(500, internal_server_error)387 return app388389When using :doc:`/blueprints`:390391.. code-block:: python392393 from flask import Blueprint394395 blog = Blueprint('blog', __name__)396397 # as a decorator398 @blog.errorhandler(500)399 def internal_server_error(e):400 return render_template('500.html'), 500401402 # or with register_error_handler403 blog.register_error_handler(500, internal_server_error)404405Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 406–407why, one step back406Blueprint Error Handlers407------------------------Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 408why, one step back408Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 409–413why, one step back409In :doc:`/blueprints`, most error handlers will work as expected.410However, there is a caveat concerning handlers for 404 and 405411exceptions. These error handlers are only invoked from an appropriate412``raise`` statement or a call to ``abort`` in another of the blueprint's413view functions; they are not invoked by, e.g., an invalid URL access.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 414why, one step back414Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 415–421why, one step back415This is because the blueprint does not "own" a certain URL space, so416the application instance has no way of knowing which blueprint error417handler it should run if given an invalid URL. If you would like to418execute different handling strategies for these errors based on URL419prefixes, they may be defined at the application level using the420``request`` proxy object.421Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 422–448why, one step back422.. code-block:: python423424 from flask import jsonify, render_template425426 # at the application level427 # not the blueprint level428 @app.errorhandler(404)429 def page_not_found(e):430 # if a request is in our blog URL space431 if request.path.startswith('/blog/'):432 # we return a custom blog 404 page433 return render_template("blog/404.html"), 404434 else:435 # otherwise we return our generic site-wide 404 page436 return render_template("404.html"), 404437438 @app.errorhandler(405)439 def method_not_allowed(e):440 # if a request has the wrong method to our API441 if request.path.startswith('/api/'):442 # we return a json saying so443 return jsonify(message="Method Not Allowed"), 405444 else:445 # otherwise we return a generic site-wide 405 page446 return render_template("405.html"), 405447448Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 449–450why, one step back449Returning API Errors as JSON450----------------------------Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 451why, one step back451Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 452why, one step back452When building APIs in Flask, some developers realise that the built-inMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 453–457why, one step back453exceptions are not expressive enough for APIs and that the content type of454:mimetype:`text/html` they are emitting is not very useful for API consumers.455456Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON457responses to API errors. :func:`~flask.abort` is calledMerge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 458why, one step back458with a ``description`` parameter. The error handler willMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 459–477why, one step back459use that as the JSON error message, and set the status code to 404.460461.. code-block:: python462463 from flask import abort, jsonify464465 @app.errorhandler(404)466 def resource_not_found(e):467 return jsonify(error=str(e)), 404468469 @app.route("/cheese")470 def get_one_cheese():471 resource = get_resource()472473 if resource is None:474 abort(404, description="Resource not found")475476 return jsonify(resource)477Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 478–479why, one step back478We can also create custom exception classes. For instance, we can479introduce a new custom exception for an API that can take a proper human readable message,Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 480–521why, one step back480a status code for the error and some optional payload to give more context481for the error.482483This is a simple example:484485.. code-block:: python486487 from flask import jsonify, request488489 class InvalidAPIUsage(Exception):490 status_code = 400491492 def __init__(self, message, status_code=None, payload=None):493 super().__init__()494 self.message = message495 if status_code is not None:496 self.status_code = status_code497 self.payload = payload498499 def to_dict(self):500 rv = dict(self.payload or ())501 rv['message'] = self.message502 return rv503504 @app.errorhandler(InvalidAPIUsage)505 def invalid_api_usage(e):506 return jsonify(e.to_dict())507508 # an API app route for getting user information509 # a correct request might be /api/user?user_id=420510 @app.route("/api/user")511 def user_api(user_id):512 user_id = request.arg.get("user_id")513 if not user_id:514 raise InvalidAPIUsage("No user id provided!")515516 user = get_user(user_id=user_id)517 if not user:518 raise InvalidAPIUsage("No such user!", status_code=404)519520 return jsonify(user.to_dict())521Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
line 522why, one step back522A view can now raise that exception with an error message. AdditionallyMerge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 523–528why, one step back523some extra payload can be provided as a dictionary through the `payload`524parameter.525526527Logging528-------Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
line 529why, one step back529Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 530–531why, one step back530See :doc:`/logging` for information about how to log exceptions, such as531by emailing them to admins.Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
lines 532–533why, one step back532533Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 534–535why, one step back534Debugging535---------Merge pull request #3594 from jackwardell/consolidating-error-pages-docsDavid Lordbefore adoption21c3df3
line 536why, one step back536Merge pull request #3669 from ebonnecab/error-docsDavid Lordbefore adoption36e6fc8
lines 537–538why, one step back537See :doc:`/debugging` for information about how to debug errors in538development and production.