Python | 404 Error Handling in Flask

We have encountered this 404 error many numbers of times. This error pops up when a page is not found. This happens when the page is deleted or maybe it’s URL got changed and so on. Now, here I am going to teach you how to handle this error. This is known as exception handling.

At first, we have to download flask

pip install flask

We write the above code in the command window in your python directory so that your python library has flask.

Next, we move forward to the code.

404 Error Handling in Flask – Python

from flask import Flask, abort
from flask import jsonify
app = Flask(__name__)

@app.errorhandler(404) 
def invalid_route(e): 
    return jsonify({'errorCode' : 404, 'message' : 'Route not found'})

This is a very basic code where I am importing some modules and handling an exception. But you have to know how this flask web actually works. Before we understand the third line, we have to know what is a flask app.

For this let’s, check out another code, to understand this flask web application framework more easily

Code:

from flask import Flask, abort
app = Flask(__name__)
@app.route("/")
def hello():
    return "Welcome to Python Flask."

When we look at this code we are creating a basic flask web application. When we enter the app URL it welcomes you but when suddenly you mistype the URL it raises an error.

This error is handled with the help of the previous code. In the third line when I mentioned the app it was this app I was talking about.

Finally, I just returned an error statement when you provide an invalid output. But you never encounter an error because the error is already excluded. That’s how the exception handling using flask works.

Also read: How to build a blogging website in Python with Flask

Leave a Reply

Your email address will not be published. Required fields are marked *