在延迟回调中引发异常

时间:2015-10-15 15:02:21

标签: python twisted

我有以下代码:

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处理,并且在添加callback3后没有添加错误处理程序,我希望抛出'Unhandled exception ...',但是没有发生。我在这里错过了什么吗?

请帮助 谢谢

1 个答案:

答案 0 :(得分: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

有多个版本的Twisted。你真的按原样运行那个确切的脚本吗?我假设您重新输入了输出,并没有复制并粘贴它,因为withTest之间只有一个空格而不是实际打印的两个空格。