python - Catching exception and handling in except: if-statement -


i have 2 possible errors in use case: 'rsa key format not supported' incorrect passphrase , 'pem encryption format not supported.' required passphrase none given. these both valueerror type.

i'm trying in try-except

from flask import flask, url_for, request, json, jsonify crypto.publickey import rsa  app = flask(__name__)  @app.route('/key2pub', methods = ['post']) def api_keypub():     if request.headers['content-type'] == 'application/json':          resp = none         try:             pubkey = rsa.importkey(request.json['key'], request.json['passphrase'])         except valueerror e:             if e == 'rsa key format not supported':                 global resp                 resp = jsonify({"error": "incorrect passphrase", "raw": e})             elif e == 'pem encryption format not supported.':                 global resp                 resp = jsonify({"error": "passphrase missing", "raw": e})          return resp  if __name__ == '__main__':     app.run(debug=true); 

i'm getting error:

... valueerror: view function did not return response 

so seems resp not getting set in except if statement.

i suspect i'm using try-except in wrong manner, can show me correct way this?

you write global resp while have local one. global resp set, local resp set none not changed, therefore return none. if remove global resp declaration should work correctly. maybe set default resp in case error miss. following

    resp = none     try:         pubkey = rsa.importkey(request.json['key'], request.json['passphrase'])     except valueerror e:         if str(e) == 'rsa key format not supported':             resp = jsonify({"error": "incorrect passphrase", "raw": str(e)})         elif str(e) == 'pem encryption format not supported.':             resp = jsonify({"error": "passphrase missing", "raw": str(e)})         else:             resp = jsonify({"error": "unexpected error", "raw": str(e)})      return resp 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -