In this tutorial, you will learn how to create custom error pages in Flask. By doing so, you will enhance the user experience of your web application by providing more informative and visually appealing error messages.
Flask allows the creation of custom error pages through the errorhandler
decorator. This decorator lets Flask know that the following function should be called when a specific HTTP error occurs.
Best practice: It's advisable to create custom error pages for the most common HTTP errors: 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (not found), and 500 (internal server error).
Now, let's create custom error pages for a 404 (not found) and 500 (internal server error) HTTP error.
@app.errorhandler(404)
def page_not_found(e):
# '404.html' is the template with your custom error message
return render_template('404.html'), 404
This code tells Flask to call the page_not_found()
function whenever a 404 error is encountered. This function will then render a custom '404.html' template.
@app.errorhandler(500)
def internal_server_error(e):
# '500.html' is the template with your custom error message
return render_template('500.html'), 500
This function works similarly to the previous one, but it handles 500 errors.
In this tutorial, we learned how to create and implement custom error pages in Flask using the errorhandler
decorator. This allows us to provide more user-friendly error messages in our web application.
For further learning, consider exploring how to create custom error pages for other HTTP error codes. You might also want to learn how to customize these pages further using CSS and Bootstrap.
Now, let's put what we've learned into practice with a few exercises:
Solutions:
1. To create a custom error page for a 400 error, use the errorhandler
decorator:
@app.errorhandler(400)
def bad_request(e):
return render_template('400.html'), 400
@app.errorhandler(401)
def unauthorized(e):
return render_template('401.html'), 401
<head>
tag of your HTML templates:<head>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>
You can then use Bootstrap classes to design your pages. For further practice, try creating more custom error pages and styling them with Bootstrap.