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.
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