2015-10-15 209 views
2

我有以下代碼:引發異常

from twisted.internet.defer import Deferred 

def callback1(result): 
    print "callback1 called with ",result 
    return result 

def callback2(result): 
    print "callback2 called with ",result 

def callback3(result): 
    raise Exception("callback 3") 

def errback(result): 
    print 'handled error' 
    return 'everything fine now' 

d = Deferred() 
d.addCallback(callback1) 
d.addCallback(callback2) 
d.addCallbacks(callback3, errback) 
d.callback("Test") 

我期望的輸出是:

callback1 called with Test 
callback2 called with Test 
Unhandled Error 
.... 

但我實際上得到的是

callback1 called with Test 
callback2 called with Test 

由於異常在回調鏈中N級提升由級別爲N + 1的errback處理,添加後沒有添加錯誤處理程序回調3,我期待'未處理的異常...'被拋出,但是這並沒有發生。我在這裏錯過了什麼嗎?

請幫助 謝謝

回答

3

運行你的榜樣,我看到了你的輸出預計:

callback1 called with Test 
callback2 called with Test 
Unhandled error in Deferred: 


Traceback (most recent call last): 
    File "t.py", line 21, in <module> 
    d.callback("Test") 
    File ".../twisted/internet/defer.py", line 393, in callback 
    self._startRunCallbacks(result) 
    File ".../twisted/internet/defer.py", line 501, in _startRunCallbacks 
    self._runCallbacks() 
--- <exception caught here> --- 
    File ".../twisted/internet/defer.py", line 588, in _runCallbacks 
    current.result = callback(current.result, *args, **kw) 
    File "t.py", line 11, in callback3 
    raise Exception("callback 3") 
exceptions.Exception: callback 3 

與扭曲的多個版本。你是否真的按原樣運行了這個確切的腳本?我假設你重新輸入了輸出,並沒有複製和粘貼,因爲你只有一個空間在withTest之間,而不是實際打印的兩個空間。

+1

感謝您的回覆雕文。你是對的,這個例子在作爲python腳本運行時會給出預期的輸出。我從Python REPL運行它。爲什麼它不會在REPL中拋出未處理的錯誤? –

+1

當'Deferred'在垃圾收集時仍處於失敗狀態時,會打印未處理的錯誤。如果用control-D退出解釋器(或在Windows上輸入control-Z),您將看到它打印出來。問題是,雖然你仍然有一個'd'的引用,你可能還會添加一個errback來處理錯誤,所以你可能會恢復。 – Glyph

+0

我現在明白了,非常感謝:) –