Invalid routes are not caught by @app.errorhandler(Exception) in flask Invalid routes are not caught by @app.errorhandler(Exception) in flask flask flask

Invalid routes are not caught by @app.errorhandler(Exception) in flask


I assume that you are only passing the app object of Flask to the Api constructor.

But, you can add another argument in the Constructor called catch_all_404s which takes a bool.

From here:

api = Api(app, catch_all_404s=True)

This should let a 404 error route to your handle_error() method.

Even after doing this, if it doesn't handle the errors your way, you could subclass the Api. From here:

class MyApi(Api):    def handle_error(self, e):        """ Overrides the handle_error() method of the Api and adds custom error handling        :param e: error object        """        code = getattr(e, 'code', 500)  # Gets code or defaults to 500        if code == 404:            return self.make_response({                'message': 'not-found',                'code': 404            }, 404)    return super(MyApi, self).handle_error(e)  # handle others the default way

And then after doing that, you could initialize your api object using the MyApi object instead of the Api object.

Like this,

api = MyApi(app, catch_all_404s=True)

Let me know if this works. This is one of my first Answers on Stack Overflow.