Custom Error Pages

Flask comes with a handy abort() function that aborts arequest with an HTTP error code early. It will also provide a plain blackand white error page for you with a basic description, but nothing fancy.

Depending on the error code it is less or more likely for the user toactually see such an error.

Common Error Codes

The following error codes are some that are often displayed to the user,even if the application behaves correctly:

  • 404 Not Found
  • The good old “chap, you made a mistake typing that URL” message. Socommon that even novices to the internet know that 404 means: damn,the thing I was looking for is not there. It’s a very good idea tomake sure there is actually something useful on a 404 page, at least alink back to the index.

  • 403 Forbidden

  • If you have some kind of access control on your website, you will haveto send a 403 code for disallowed resources. So make sure the useris not lost when they try to access a forbidden resource.

  • 410 Gone

  • Did you know that there the “404 Not Found” has a brother named “410Gone”? Few people actually implement that, but the idea is thatresources that previously existed and got deleted answer with 410instead of 404. If you are not deleting documents permanently fromthe database but just mark them as deleted, do the user a favour anduse the 410 code instead and display a message that what they werelooking for was deleted for all eternity.

  • 500 Internal Server Error

  • Usually happens on programming errors or if the server is overloaded.A terribly good idea is to have a nice page there, because yourapplication will fail sooner or later (see also:Application Errors).

Error Handlers

An error handler is a function that returns a response when a type of error israised, similar to how a view is a function that returns a response when arequest URL is matched. It is passed the instance of the error being handled,which is most likely a HTTPException. An errorhandler for “500 Internal Server Error” will be passed uncaught exceptions inaddition to explicit 500 errors.

An error handler is registered with the errorhandler()decorator or the register_error_handler() method. A handlercan be registered for a status code, like 404, or for an exception class.

The status code of the response will not be set to the handler’s code. Makesure to provide the appropriate HTTP status code when returning a response froma handler.

A handler for “500 Internal Server Error” will not be used when running indebug mode. Instead, the interactive debugger will be shown.

Here is an example implementation for a “404 Page Not Found” exception:

  1. from flask import render_template
  2.  
  3. @app.errorhandler(404)
  4. def page_not_found(e):
  5. # note that we set the 404 status explicitly
  6. return render_template('404.html'), 404

When using the application factory pattern:

  1. from flask import Flask, render_template
  2.  
  3. def page_not_found(e):
  4. return render_template('404.html'), 404
  5.  
  6. def create_app(config_filename):
  7. app = Flask(__name__)
  8. app.register_error_handler(404, page_not_found)
  9. return app

An example template might be this:

  1. {% extends "layout.html" %}
  2. {% block title %}Page Not Found{% endblock %}
  3. {% block body %}
  4. <h1>Page Not Found</h1>
  5. <p>What you were looking for is just not there.
  6. <p><a href="{{ url_for('index') }}">go somewhere nice</a>
  7. {% endblock %}

Returning API errors as JSON

When using Flask for web APIs, you can use the same techniques as aboveto return JSON responses to API errors. abort() is calledwith a description parameter. The errorhandler() willuse that as the JSON error message, and set the status code to 404.

  1. from flask import abort, jsonify
  2.  
  3. @app.errorhandler(404)
  4. def resource_not_found(e):
  5. return jsonify(error=str(e)), 404
  6.  
  7. @app.route("/cheese")
  8. def get_one_cheese():
  9. resource = get_resource()
  10.  
  11. if resource is None:
  12. abort(404, description="Resource not found")
  13.  
  14. return jsonify(resource)