Creating custom 4xx and 5xx error handlers
Every application throws errors to users at some point in time. These errors can be due to a user typing a non-existent URL (404
), application overload (500
), or something forbidden for a certain user to access (403
). A good application handles these errors in a user-interactive way instead of showing an ugly white page, which makes no sense to most users. Flask provides an easy-to-use decorator to handle these errors. In this recipe, we will understand how we can leverage this decorator.
Getting ready
The Flask app
object has a method called errorhandler()
, which enables us to handle our application’s errors in a much more beautiful and efficient manner.
How to do it...
Create a method that is decorated with errorhandler()
and renders the 404.html
template whenever the 404 Not Found
error occurs:
@app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404...