如何在扭曲的延迟回调中捕获异常?

时间:2011-10-28 11:36:44

标签: python twisted deferred

    from twisted.internet import reactor, defer

def getDummyData(x):
    """
    This function is a dummy which simulates a delayed result and
    returns a Deferred which will fire with that result. Don't try too
    hard to understand this.
    """
    d = defer.Deferred()
    # simulate a delayed result by asking the reactor to fire the
    # Deferred in 2 seconds time with the result x * 3
    reactor.callLater(2, d.callback, x * 3)
    return d

def printData(d):
    """
    Data handling function to be added as a callback: handles the
    data by printing the result
    """
    raise ValueError('IIIGGAA')
    print d

def nextCall(d):
    import pdb; pdb.set_trace()
d = getDummyData(3)

d.addErrback(nextCall).addCallback(printData).addErrback(nextCall).addCallback(nextCall)


# manually set up the end of the process by asking the reactor to
# stop itself in 4 seconds time
reactor.callLater(1, reactor.stop)
# start up the Twisted reactor (event loop handler) manually
reactor.run()

函数nextCall - 从不调用。那么我能找到我的ValueError吗?

感谢。

1 个答案:

答案 0 :(得分:4)

它从未被调用过,因为你的评论中的代码表示它要求反应堆在 4 秒内停止运行实际上要求反应堆在 1 秒内停止运行。永远不会调用2秒callLater,因此永远不会触发d,因此永远不会调用nextCall

也许您应该尝试在不使用reactor的情况下构建此示例,只需在适当的延迟上同时调用callback?你不需要反应器来触发一个简单的Deferred,同时搞乱它们可以帮助你更准确地了解什么时候会发生什么。