errorpages.rst
This file
Path
docs/patterns/errorpages.rst
123 lines · 4.3 KiB
Last changed by
remove unused ref directivesDavid Lordbefore adoption171aabc
History of this fileTake it
1Custom Error Pages2==================34Flask comes with a handy :func:`~flask.abort` function that aborts a5request with an HTTP error code early. It will also provide a plain black6and white error page for you with a basic description, but nothing fancy.78Depending on the error code it is less or more likely for the user to9actually see such an error.1011Common Error Codes12------------------1314The following error codes are some that are often displayed to the user,15even if the application behaves correctly:1617*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.2324*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.2829*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.3738*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`).434445Error Handlers46--------------4748An error handler is a function that returns a response when a type of error is49raised, similar to how a view is a function that returns a response when a50request URL is matched. It is passed the instance of the error being handled,51which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error52handler for "500 Internal Server Error" will be passed uncaught exceptions in53addition to explicit 500 errors.5455An error handler is registered with the :meth:`~flask.Flask.errorhandler`56decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler57can be registered for a status code, like 404, or for an exception class.5859The status code of the response will not be set to the handler's code. Make60sure to provide the appropriate HTTP status code when returning a response from61a handler.6263A handler for "500 Internal Server Error" will not be used when running in64debug mode. Instead, the interactive debugger will be shown.6566Here is an example implementation for a "404 Page Not Found" exception::6768 from flask import render_template6970 @app.errorhandler(404)71 def page_not_found(e):72 # note that we set the 404 status explicitly73 return render_template('404.html'), 4047475When using the :doc:`appfactories`::7677 from flask import Flask, render_template7879 def page_not_found(e):80 return render_template('404.html'), 4048182 def create_app(config_filename):83 app = Flask(__name__)84 app.register_error_handler(404, page_not_found)85 return app8687An example template might be this:8889.. sourcecode:: html+jinja9091 {% 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 %}9899100Returning API errors as JSON101----------------------------102103When using Flask for web APIs, you can use the same techniques as above104to return JSON responses to API errors. :func:`~flask.abort` is called105with a ``description`` parameter. The :meth:`~flask.errorhandler` will106use that as the JSON error message, and set the status code to 404.107108.. code-block:: python109110 from flask import abort, jsonify111112 @app.errorhandler(404)113 def resource_not_found(e):114 return jsonify(error=str(e)), 404115116 @app.route("/cheese")117 def get_one_cheese():118 resource = get_resource()119120 if resource is None:121 abort(404, description="Resource not found")122123 return jsonify(resource)