如何将对象从回调传递给errback(扭曲)?

时间:2016-06-06 18:58:01

标签: python twisted deferred

我有一个带有errback的回调链。如果任何回调失败,我需要传递一个在errBack上使用的对象。

如何将对象从回调传递给errback?

以下代码举例说明了我想要做的事情:

from twisted.internet.defer import FAILURE
from twisted.internet import defer


class CodMsg(object):
    def __init__(self, code, msg):
        self.code = code
        self.msg = msg

class Resource(object):

    @classmethod
    def checkCondition(cls, result):
        if result == "error":
            cdm = CodMsg(1, 'Error 1')
            raise FAILURE, cdm
        else:
            return "ok"

    @classmethod
    def erBackTst (cls, result):

        ####### How to get the value of cdm here? ########  <<<===
        print 'Error:'
        print result
        return result


d = defer.Deferred()

d.addCallback(Resource.checkCondition)


d.addErrback(Resource.erBackTst)

d.callback("error")

print d.result

1 个答案:

答案 0 :(得分:1)

在这种情况下,您只需引发一个例外,其中包含您需要的所有信息

例如:

from twisted.internet import defer

class MyCustomException(Exception):
    def __init__(self, msg, code):
        self.code = code
        self.message = msg

def callback(result):
    print result
    raise MyCustomException('Message', 23)

def errback(failure):
    # failure.value is an exception instance that you raised in callback
    print failure.value.message
    print failure.value.code

d = defer.Deferred()
d.addCallback(callback)
d.addErrback(errback)

d.callback("error")

另外,为了更好地理解deffered和异步编程,你可以阅读这篇精彩的扭曲教程http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/。 它在示例中使用了一点点过时的扭曲版本,但它仍然是开始学习扭曲的优秀来源