Skip to content
Myr

adjust header levels and spacing

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

use code-block consistently

authored by David Lord · committed by David Lord · parent 2db3c9a · Browse files · 1 file+37 added−28 removed
This commit

State

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

Diff stats

1 file+37 added−28 removed

  • other:+37 added−28 removed

1 file+37 added−28 removed

modified:docs/errorhandling.rst+37 added-28 removed
99 unmodified lines
100 <https://docs.sentry.io/platforms/python/>`_ for more information.101* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_102* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.103104105.. _error-handlers:106107Error Handlers108--------------
9 unmodified lines
118The status code of the response will not be set to the handler's code. Make119sure to provide the appropriate HTTP status code when returning a response from120a handler.121122123Registering124```````````125126Register handlers by decorating a function with127:meth:`~flask.Flask.errorhandler`. Or use128:meth:`~flask.Flask.register_error_handler` to register the function later.127Remember to set the error code when returning the response. ::129Remember to set the error code when returning the response.130131.. code-block:: python132133 @app.errorhandler(werkzeug.exceptions.BadRequest)134 def handle_bad_request(e):135 return 'bad request!', 400136
6 unmodified lines
143144Non-standard HTTP codes cannot be registered by code because they are not known145by Werkzeug. Instead, define a subclass of146:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and143register and raise that exception class. ::147register and raise that exception class.148149.. code-block:: python150151 class InsufficientStorage(werkzeug.exceptions.HTTPException):152 code = 507153 description = 'Not enough storage space.'154
5 unmodified lines
160:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status161codes. Handlers can be registered for a specific class, or for all subclasses162of a parent class.163164165Handling166````````167168When building a Flask application you *will* run into exceptions. If some part
28 unmodified lines
197raises the exception. However, the blueprint cannot handle 404 routing errors198because the 404 occurs at the routing level before the blueprint can be199determined.200201202Generic Exception Handlers203``````````````````````````204205It is possible to register error handlers for very generic base classes
24 unmodified lines
230 })231 response.content_type = "application/json"232 return response233226234An error handler for ``Exception`` might seem useful for changing how235all errors, even unhandled ones, are presented to the user. However,236this is similar to doing ``except Exception:`` in Python, it will237capture *all* otherwise unhandled errors, including all HTTP status
20 unmodified lines
258register handlers for both ``HTTPException`` and ``Exception``, the259``Exception`` handler will not handle ``HTTPException`` subclasses260because it the ``HTTPException`` handler is more specific.261262263Unhandled Exceptions264````````````````````265266When there is no error handler registered for an exception, a 500
26 unmodified lines
293An error handler for "500 Internal Server Error" will be passed uncaught exceptions in294addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.295Instead, the interactive debugger will be shown.296297298Custom Error Pages299------------------300301Sometimes when building a Flask application, you might want to raise a
29 unmodified lines
331 abort(404)332333 return render_template("profile.html", user=user)334326Here is another example implementation for a "404 Page Not Found" exception::335Here is another example implementation for a "404 Page Not Found" exception:336337.. code-block:: python338339 from flask import render_template340341 @app.errorhandler(404)342 def page_not_found(e):343 # note that we set the 404 status explicitly344 return render_template('404.html'), 404345335When using :doc:`/patterns/appfactories`::346When using :doc:`/patterns/appfactories`:347348.. code-block:: python349350 from flask import Flask, render_template351352 def page_not_found(e):353 return render_template('404.html'), 404
4 unmodified lines
358 return app359360An example template might be this:361349.. sourcecode:: html+jinja362.. code-block:: html+jinja363364 {% extends "layout.html" %}365 {% block title %}Page Not Found{% endblock %}366 {% block body %}
1 unmodified line
368 <p>What you were looking for is just not there.369 <p><a href="{{ url_for('index') }}">go somewhere nice</a>370 {% endblock %}371372373Further Examples374````````````````375376The above examples wouldn't actually be an improvement on the default377exception pages. We can create a custom 500.html template like this:378365.. sourcecode:: html+jinja379.. code-block:: html+jinja380381 {% extends "layout.html" %}382 {% block title %}Internal Server Error{% endblock %}383 {% block body %}
12 unmodified lines
396 def internal_server_error(e):397 # note that we set the 500 status explicitly398 return render_template('500.html'), 500399386400When using :doc:`/patterns/appfactories`:401402.. code-block:: python403391404 from flask import Flask, render_template405406 def internal_server_error(e):407 return render_template('500.html'), 500
2 unmodified lines
410 app = Flask(__name__)411 app.register_error_handler(500, internal_server_error)412 return app413402414When using :doc:`/blueprints`:415416.. code-block:: python417
8 unmodified lines
426427 # or with register_error_handler428 blog.register_error_handler(500, internal_server_error)429419Blueprint Error Handling420````````````````````````430422In blueprints, error handlers will work as expected. However, there is a caveat423concerning handlers for 404 and 405 exceptions. These error handlers are only424invoked from an appropriate ``raise`` statement or a call to ``abort`` in another425of the blueprint's view functions; they are not invoked by, e.g., an invalid URL426access.431Blueprint Error Handlers432------------------------433434In :doc:`/blueprints`, most error handlers will work as expected.435However, there is a caveat concerning handlers for 404 and 405436exceptions. These error handlers are only invoked from an appropriate437``raise`` statement or a call to ``abort`` in another of the blueprint's438view functions; they are not invoked by, e.g., an invalid URL access.439440This is because the blueprint does not "own" a certain URL space, so429the application instance has no way of knowing which blueprint error handler it430should run if given an invalid URL. If you would like to execute different431handling strategies for these errors based on URL prefixes, they may be defined432at the application level using the ``request`` proxy object:441the application instance has no way of knowing which blueprint error442handler it should run if given an invalid URL. If you would like to443execute different handling strategies for these errors based on URL444prefixes, they may be defined at the application level using the445``request`` proxy object.446447.. code-block:: python448449 from flask import jsonify, render_template
9 unmodified lines
459 else:460 # otherwise we return our generic site-wide 404 page461 return render_template("404.html"), 404462450463 @app.errorhandler(405)464 def method_not_allowed(e):465 # if a request has the wrong method to our API466 if request.path.startswith('/api/'):
3 unmodified lines
470 # otherwise we return a generic site-wide 405 page471 return render_template("405.html"), 405472473474Returning API Errors as JSON475----------------------------476463For more information on Blueprint Error Handling see :ref:`my-blueprint-error-label`.464465Returning API errors as JSON466````````````````````````````467477When building APIs in Flask, some developers realise that the built-in478exceptions are not expressive enough for APIs and that the content type of479:mimetype:`text/html` they are emitting is not very useful for API consumers.480
62 unmodified lines
543 raise InvalidAPIUsage("No such user!", status_code=404)544545 return jsonify(user.to_dict())546538547A view can now raise that exception with an error message. Additionally548some extra payload can be provided as a dictionary through the `payload`549parameter.550551552Logging553-------554555See :doc:`/logging` for information on how to log exceptions, such as by
59 unmodified lines