flask.Flask.errorhandler

Flask.errorhandler(*args, **kwargs)[source]

A decorator that is used to register a function give a given error code. Example:

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

You can also register handlers for arbitrary exceptions:

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500

You can also register a function as error handler without using the errorhandler() decorator. The following example is equivalent to the one above:

def page_not_found(error):
    return 'This page does not exist', 404
app.error_handler_spec[None][404] = page_not_found

Setting error handlers via assignments to error_handler_spec however is discouraged as it requires fiddling with nested dictionaries and the special case for arbitrary exception types.

The first None refers to the active blueprint. If the error handler should be application wide None shall be used.

New in version 0.7: Use register_error_handler() instead of modifying error_handler_spec directly, for application wide error handlers.

New in version 0.7: One can now additionally also register custom exception types that do not necessarily have to be a subclass of the HTTPException class.

Parameters:code – the code as integer for the handler