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
Provenance
- Commit
ba118b4- Tree
42018e4- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
2db3c9a
1 file changed+37 added−28 removed
modified:docs/errorhandling.rst+37 added-28 removed
99 unmodified lines100 <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/>`_.103 104+105 .. _error-handlers:106 107 Error Handlers108 --------------9 unmodified lines118 The status code of the response will not be set to the handler's code. Make119 sure to provide the appropriate HTTP status code when returning a response from120 a handler.121 122+123 Registering124 ```````````125 126 Register handlers by decorating a function with127 :meth:`~flask.Flask.errorhandler`. Or use128 :meth:`~flask.Flask.register_error_handler` to register the function later.127-Remember to set the error code when returning the response. ::129+Remember to set the error code when returning the response.130 131+.. code-block:: python132+133 @app.errorhandler(werkzeug.exceptions.BadRequest)134 def handle_bad_request(e):135 return 'bad request!', 400136 6 unmodified lines143 144 Non-standard HTTP codes cannot be registered by code because they are not known145 by Werkzeug. Instead, define a subclass of146 :class:`~werkzeug.exceptions.HTTPException` with the appropriate code and143-register and raise that exception class. ::147+register and raise that exception class.148 149+.. code-block:: python150+151 class InsufficientStorage(werkzeug.exceptions.HTTPException):152 code = 507153 description = 'Not enough storage space.'154 5 unmodified lines160 :exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status161 codes. Handlers can be registered for a specific class, or for all subclasses162 of a parent class.163 164+165 Handling166 ````````167 168 When building a Flask application you *will* run into exceptions. If some part28 unmodified lines197 raises the exception. However, the blueprint cannot handle 404 routing errors198 because the 404 occurs at the routing level before the blueprint can be199 determined.200 201+202 Generic Exception Handlers203 ``````````````````````````204 205 It is possible to register error handlers for very generic base classes24 unmodified lines230 })231 response.content_type = "application/json"232 return response233 226-234 An error handler for ``Exception`` might seem useful for changing how235 all errors, even unhandled ones, are presented to the user. However,236 this is similar to doing ``except Exception:`` in Python, it will237 capture *all* otherwise unhandled errors, including all HTTP status20 unmodified lines258 register handlers for both ``HTTPException`` and ``Exception``, the259 ``Exception`` handler will not handle ``HTTPException`` subclasses260 because it the ``HTTPException`` handler is more specific.261 262+263 Unhandled Exceptions264 ````````````````````265 266 When there is no error handler registered for an exception, a 50026 unmodified lines293 An error handler for "500 Internal Server Error" will be passed uncaught exceptions in294 addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.295 Instead, the interactive debugger will be shown.296 297+298 Custom Error Pages299 ------------------300 301 Sometimes when building a Flask application, you might want to raise a29 unmodified lines331 abort(404)332 333 return render_template("profile.html", user=user)334 326-Here is another example implementation for a "404 Page Not Found" exception::335+Here is another example implementation for a "404 Page Not Found" exception:336 337+.. code-block:: python338+339 from flask import render_template340 341 @app.errorhandler(404)342 def page_not_found(e):343 # note that we set the 404 status explicitly344 return render_template('404.html'), 404345 335-When using :doc:`/patterns/appfactories`::346+When using :doc:`/patterns/appfactories`:347 348+.. code-block:: python349+350 from flask import Flask, render_template351 352 def page_not_found(e):353 return render_template('404.html'), 4044 unmodified lines358 return app359 360 An example template might be this:361 349-.. sourcecode:: html+jinja362+.. code-block:: html+jinja363 364 {% extends "layout.html" %}365 {% block title %}Page Not Found{% endblock %}366 {% block body %}1 unmodified line368 <p>What you were looking for is just not there.369 <p><a href="{{ url_for('index') }}">go somewhere nice</a>370 {% endblock %}371 372+373 Further Examples374 ````````````````375 376 The above examples wouldn't actually be an improvement on the default377 exception pages. We can create a custom 500.html template like this:378 365-.. sourcecode:: html+jinja379+.. code-block:: html+jinja380 381 {% extends "layout.html" %}382 {% block title %}Internal Server Error{% endblock %}383 {% block body %}12 unmodified lines396 def internal_server_error(e):397 # note that we set the 500 status explicitly398 return render_template('500.html'), 500399 386-400 When using :doc:`/patterns/appfactories`:401 402 .. code-block:: python403 391-404 from flask import Flask, render_template405 406 def internal_server_error(e):407 return render_template('500.html'), 5002 unmodified lines410 app = Flask(__name__)411 app.register_error_handler(500, internal_server_error)412 return app413 402-414 When using :doc:`/blueprints`:415 416 .. code-block:: python417 8 unmodified lines426 427 # or with register_error_handler428 blog.register_error_handler(500, internal_server_error)429 419-Blueprint Error Handling420-````````````````````````430 422-In blueprints, error handlers will work as expected. However, there is a caveat423-concerning handlers for 404 and 405 exceptions. These error handlers are only424-invoked from an appropriate ``raise`` statement or a call to ``abort`` in another425-of the blueprint's view functions; they are not invoked by, e.g., an invalid URL426-access.431+Blueprint Error Handlers432+------------------------433 434+In :doc:`/blueprints`, most error handlers will work as expected.435+However, there is a caveat concerning handlers for 404 and 405436+exceptions. These error handlers are only invoked from an appropriate437+``raise`` statement or a call to ``abort`` in another of the blueprint's438+view functions; they are not invoked by, e.g., an invalid URL access.439+440 This is because the blueprint does not "own" a certain URL space, so429-the application instance has no way of knowing which blueprint error handler it430-should run if given an invalid URL. If you would like to execute different431-handling strategies for these errors based on URL prefixes, they may be defined432-at the application level using the ``request`` proxy object:441+the application instance has no way of knowing which blueprint error442+handler it should run if given an invalid URL. If you would like to443+execute different handling strategies for these errors based on URL444+prefixes, they may be defined at the application level using the445+``request`` proxy object.446 447 .. code-block:: python448 449 from flask import jsonify, render_template9 unmodified lines459 else:460 # otherwise we return our generic site-wide 404 page461 return render_template("404.html"), 404462 450-463 @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 lines470 # otherwise we return a generic site-wide 405 page471 return render_template("405.html"), 405472 473 474+Returning API Errors as JSON475+----------------------------476 463-For more information on Blueprint Error Handling see :ref:`my-blueprint-error-label`.464-465-Returning API errors as JSON466-````````````````````````````467-477 When building APIs in Flask, some developers realise that the built-in478 exceptions 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 lines543 raise InvalidAPIUsage("No such user!", status_code=404)544 545 return jsonify(user.to_dict())546 538-547 A view can now raise that exception with an error message. Additionally548 some extra payload can be provided as a dictionary through the `payload`549 parameter.550 551+552 Logging553 -------554 555 See :doc:`/logging` for information on how to log exceptions, such as by59 unmodified lines