errorpages.rst
This file
Path
docs/patterns/errorpages.rst
125 lines · 4.4 KiB
Last changed by
Merge pull request #3260 from LBWright/error-handlingDavid Lordbefore adoptionf7f1d9d
History of this fileTake it
1.. _errorpages:23Custom Error Pages4==================56Flask comes with a handy :func:`~flask.abort` function that aborts a7request with an HTTP error code early. It will also provide a plain black8and white error page for you with a basic description, but nothing fancy.910Depending on the error code it is less or more likely for the user to11actually see such an error.1213Common Error Codes14------------------1516The following error codes are some that are often displayed to the user,17even if the application behaves correctly:1819*404 Not Found*20 The good old "chap, you made a mistake typing that URL" message. So21 common that even novices to the internet know that 404 means: damn,22 the thing I was looking for is not there. It's a very good idea to23 make sure there is actually something useful on a 404 page, at least a24 link back to the index.2526*403 Forbidden*27 If you have some kind of access control on your website, you will have28 to send a 403 code for disallowed resources. So make sure the user29 is not lost when they try to access a forbidden resource.3031*410 Gone*32 Did you know that there the "404 Not Found" has a brother named "41033 Gone"? Few people actually implement that, but the idea is that34 resources that previously existed and got deleted answer with 41035 instead of 404. If you are not deleting documents permanently from36 the database but just mark them as deleted, do the user a favour and37 use the 410 code instead and display a message that what they were38 looking for was deleted for all eternity.3940*500 Internal Server Error*41 Usually happens on programming errors or if the server is overloaded.42 A terribly good idea is to have a nice page there, because your43 application *will* fail sooner or later (see also:44 :ref:`application-errors`).454647Error Handlers48--------------4950An error handler is a function that returns a response when a type of error is51raised, similar to how a view is a function that returns a response when a52request URL is matched. It is passed the instance of the error being handled,53which is most likely a :exc:`~werkzeug.exceptions.HTTPException`. An error54handler for "500 Internal Server Error" will be passed uncaught exceptions in55addition to explicit 500 errors.5657An error handler is registered with the :meth:`~flask.Flask.errorhandler`58decorator or the :meth:`~flask.Flask.register_error_handler` method. A handler59can be registered for a status code, like 404, or for an exception class.6061The status code of the response will not be set to the handler's code. Make62sure to provide the appropriate HTTP status code when returning a response from63a handler.6465A handler for "500 Internal Server Error" will not be used when running in66debug mode. Instead, the interactive debugger will be shown.6768Here is an example implementation for a "404 Page Not Found" exception::6970 from flask import render_template7172 @app.errorhandler(404)73 def page_not_found(e):74 # note that we set the 404 status explicitly75 return render_template('404.html'), 4047677When using the :ref:`application factory pattern <app-factories>`::7879 from flask import Flask, render_template8081 def page_not_found(e):82 return render_template('404.html'), 4048384 def create_app(config_filename):85 app = Flask(__name__)86 app.register_error_handler(404, page_not_found)87 return app8889An example template might be this:9091.. sourcecode:: html+jinja9293 {% extends "layout.html" %}94 {% block title %}Page Not Found{% endblock %}95 {% block body %}96 <h1>Page Not Found</h1>97 <p>What you were looking for is just not there.98 <p><a href="{{ url_for('index') }}">go somewhere nice</a>99 {% endblock %}100101102Returning API errors as JSON103----------------------------104105When using Flask for web APIs, you can use the same techniques as above106to return JSON responses to API errors. :func:`~flask.abort` is called107with a ``description`` parameter. The :meth:`~flask.errorhandler` will108use that as the JSON error message, and set the status code to 404.109110.. code-block:: python111112 from flask import abort, jsonify113114 @app.errorhandler(404)115 def resource_not_found(e):116 return jsonify(error=str(e)), 404117118 @app.route("/cheese")119 def get_one_cheese():120 resource = get_resource()121122 if resource is None:123 abort(404, description="Resource not found")124125 return jsonify(resource)