![]() |
VOOZH | about |
A 404 Error occurs when a page is not found. This can happen due to several reasons:
To improve user experience, websites should have a custom error page instead of showing a generic, unappealing one. GeeksforGeeks also uses a custom error page. For example, if we visit www.geeksforgeeks.org/ajneawnewiaiowjf, we'll see it in action.
A custom error page improves user experience by providing a clean layout, navigation options, or auto-redirecting to the homepage. Flask lets us handle errors and display a custom page easily.
Before diving further in to the topic, make sure to Install and set up Flask
We will create app.py to manage templates, 404.html to handle 404 errors, and header.html for the website's header and navbar. Let's look at their code one by one:
Flask allows defining routes and functions in a Python file so create an app.py file for our main flask app. We set up the main page route ('/') and a 404 error handler using Flask's built-in function.
The above python program will return 404.html file whenever the user opens a broken link.
The header.html file is a reusable template that contains the navbar and common page structure. It helps keep the code clean by avoiding repetition and makes updates easier. Other pages, like 404.html, extend it to maintain a consistent layout.
The app.py code for this example stays the same as above. The following code Shows the Custom 404 Error page and starts a countdown of 5 seconds. After 5 seconds are completed, it redirects the user back to the homepage.
Following code exports header and navbar from header.html. Both files should be stored in the templates. After 5 seconds, the user will get redirected to the Home Page Automatically.
Let's run the app using command - "python app.py", it will rener the home page which will look like this -
Now let's try to visit some random URL "http://127.0.0.1:5000/random_url", the custom error page will look like this -