Flask Middleware Class Raise Exception Not Catching

Viewed 296

Here is part of app.py:

app = Flask(__name__)
app.config.from_object('SETTINGS')
app.wsgi_app = Middleware(app.wsgi_app, app)


@app.errorhandler(ValueError)
def all_exception_handler(error):
    print('Error Catched!')
    return 'Error Handler', 500

And here is part of Middleware class:

class Middleware:
    def __init__(self, wsgi, app):
        self.wsgi = wsgi
        self.app = app


    def __call__(self, environ, start_response):

        raise ValueError('Value Error')

        return self.wsgi(environ, start_response)

So my issue is when I raise ValueError exception inside Middleware (raise ValueError('Value Error') the @app.errorhandler(ValueError) is not triggering thus I'm not receiving print('Error Catched!') in my console

1 Answers

Hello again my friend

I told you that Middlewares is out of app layer(outside of the request / outside of the Flask application etc) => application error handler will not work. Just move your logic into @app.before_request or app.before_request_funcs

Related