0

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.

Community
  • 1
  • 1
Andrei O
  • 325
  • 3
  • 9

1 Answers1

1

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')
jackInTheBox
  • 62
  • 1
  • 8
omab
  • 3,721
  • 19
  • 23
  • Thanks for your reply! I tried it out, it gets inside the `if` but seems to ignore the `return`. Apparently `teardown_request` functions _are not allowed to modify the request, and their return values are ignored_ (http://flask.pocoo.org/docs/api/#flask.Flask.teardown_request). – Andrei O Feb 24 '14 at 22:07
  • The updated approach works like a charm. For others implementing this, don't forget to set `DEBUG = False` and `TEST = False` in your config to test this, otherwise the exception in displayed and the error handler never called. Also note you can't `flash` within the error handler, but you can of course redirect to a page that does. – Andrei O Mar 01 '14 at 11:25
  • I've added a section about it in the docs http://psa.matiasaguirre.net/docs/configuration/flask.html#exceptions-handling – omab Mar 01 '14 at 18:33
  • Sounds good, thanks for following up and for the very useful app! – Andrei O Mar 02 '14 at 20:16