Search code examples
pythonflaskpython-social-auth

What is the right way of handling python-social-auth exceptions when using Flask?


I'm adding PSU to a Flask app and all is going pretty well so far, but I can't figure out how to handle the exceptions raised by PSU. One such exception is social.exceptions.AuthCanceled, raised when a user decides to cancel the auth process. I would obviously want to catch that and display some message.

I found a similar question on how to do this in Django by creating a new Middleware. However, that approach seems to use middleware.py defined only in PSU's django_app (and not in the flask_app).

I have some experience with Flask but haven't added Middleware before, and I'm not sure this is the right direction.


Solution

  • UPDATE

    Try defining an errorhandler (docs at http://flask.pocoo.org/docs/api/#flask.Flask.errorhandler), like this:

    @app.errorhandler(500)  # since exceptions will produce 500 errors
    def error_handler(error):
        if isinstance(error, SocialAuthBaseException):
            return redirect('/error')
    

    The solution below this line won't work


    Try with a teardown_request (http://flask.pocoo.org/docs/reqcontext/#teardown-callbacks), like this

    @app.teardown_request
    def teardown_handler(exception=None):
        if exception and isinstance(exception, SocialAuthBaseException):
            return redirect('/error')