如何将对象从回调传递到 errback(扭曲)?
How to pass an object from callback to errback (twisted)?
我有一个回调链,最后有一个 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
在这种情况下,您可以引发异常,其中包含您需要的所有信息
例如:
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")
此外,为了更好地理解延迟和异步编程,您可以阅读这个不错的扭曲教程 http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/。
它在示例中使用了一些过时的扭曲版本,但它仍然是开始学习扭曲的绝佳资源
我有一个回调链,最后有一个 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
在这种情况下,您可以引发异常,其中包含您需要的所有信息
例如:
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")
此外,为了更好地理解延迟和异步编程,您可以阅读这个不错的扭曲教程 http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/。 它在示例中使用了一些过时的扭曲版本,但它仍然是开始学习扭曲的绝佳资源