Error Handling

Errors can be handled by Flask, or by configuring the web server to point errors to certain pages. Doing the error handling in Flask is more complex, but lets you have more control over how the errors are handled.

Two primary methods exist:

Error by blueprint

  1. Create one or more error handlers
    1. Use this decorator: @bp.errorhandler(Exception)
      1. bp is the blueprint to be used
      2. Exception is the particular exception that you want this error handler to work with
        1. Flask will use the most specific exception handler first, falling back to more general exceptions
        2. If no error handler is found, then it falls back to the default error handling (showing stack trace in debug mode)
    2. Define the function, and tell it what to return, where it can take a single argument, of the class of the Exception
      1. One of the most basic is to create a jinja template for errors and return the template: 

Error by app

In this case you can register a single blueprint to handle all errors for the flask app.

To implement this:

  1. Create the error handlers as above
    1. Rather than the decorator used above use: @bp.app_errorhandler(Exception)
    2. The parts are the same as above
  2. Register the blueprint for the error handlers
    1. import the file containing the error handlers into the file where you initialize Flask and register the blueprints 
    2. app.register_blueprint(errors.bp, url_prefix=prefix, static_folder="static")
      1. app is the defined Flask object
      2. errors is the file name of the error handlers
      3. bp is the name of the blueprint defined in the errors file

Simple example (error by app)

errors
from flask import Blueprint, render_template

bp = Blueprint("errors", __name__)

@bp.app_errorhandler(Exception)
def handle_all_errors(e):
	return render_template("pages/error.html", err=e)


  • No labels