0

I am developing a async web service with Twisted Klein. Part of the code are as follows:

@inlineCallbacks
def test(input1): 
    try:
        result = yield function(input1)
        print result
        returnValue(result)
    except:
        returnValue("None")
        pass

I have this test function as part of my web service, every time I called the test function from other function in returns "None". However, On the server screen it prints out the correct result I want (The print result line in try is correctly executed, just the returnValue(result) is not used). I am not very familiar with async coding, but is there anything I should be careful about try except together with yield? Thanks.

JLTChiu
  • 983
  • 3
  • 12
  • 28
  • 3
    Why are you using a bare `except`? You should catch the specific exception type you're expecting. I don't know much about Twisted Klein, but a quick Google search says they're [using exceptions to simulate coroutines](http://tavendo.com/blog/post/going-asynchronous-from-flask-to-twisted-klein/), so a bare `except` would screw with that pretty hard. – user2357112 Jun 07 '16 at 17:49
  • So I modify this from a flask code, and I am calling an api that might throws back exception, I don't want it to crash so I use try/except to do that. Maybe I should remove that bare except and see how it works? – JLTChiu Jun 07 '16 at 17:53
  • It actually worked after I removed the bare except. I guess I need to specify all of the possible exceptions from the api then. I wish to label you as the correct answer but you are in a comment – JLTChiu Jun 07 '16 at 17:54

1 Answers1

2

First of all you should never have a bare except clause. (there are exceptions, but generally speaking it's better to catch specific errors.)

Second, from the twisted docs on returnValue:

Note: this is currently implemented by raising an exception derived from BaseException. You might want to change any 'except:' clauses to an 'except Exception:' clause so as not to catch this exception.

Also: while this function currently will work when called from within arbitrary functions called from within the generator, do not rely upon this behavior.

What's happening is your correct result is printing, then you call returnValue, which raises an exception, causing your code to return None

twisted docs

Community
  • 1
  • 1
Jonathan Holmes
  • 438
  • 2
  • 12