如何在Twisted的Deferred回调中捕获异常?

2 投票
1 回答
776 浏览
提问于 2025-04-17 05:10
    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 个回答

4

你提到的代码其实从来没有被调用,因为你评论下的那段代码是让反应器在1秒后自己停止,而不是4秒。那个2秒的callLater根本没被调用,所以d也就没被触发,结果nextCall也没被调用。

或许你可以试着不使用反应器,直接在合适的时候同步调用callback?其实你不需要反应器就能触发一个简单的Deferred,这样同步操作可以帮助你更清楚地理解到底发生了什么。

撰写回答