Customize errors in Flask

We have already seen in an article how we can handle error pages in Flask. However, what we saw was how to generate standard error pages. In this case we are going to see how we can customize errors in Flask.

To manage the error we are going to use the abort() method, to which we will pass the error code to be returned.

@app.route('/blocked')
def locked():
    return abort(401)

So far everything is correct, since we will have the standard 401 error page as a response to calling the /blocked route.

To be able to customize errors in Flask we must use an annotation with a errorhandler() to which we will indicate the error code that we are managing.

@app.errorhandler(401)

The method that we assign as a controller will receive an error object as a parameter:

@app.errorhandler(401)
def access_error(error):

And the content to be returned depends on what we want to do. Although the most common thing will be to return a template using the render_template() method.

What we must not forget is that in the response we must indicate the error code again, so that it is returned to the client.

@app.errorhandler(401)
def access_error(error):
    return render_template('error_401.html'), 401

So we have already seen how easy it is to customize errors in Flask using annotations.