2016-06-06 89 views
0

我有在端部的errback可回調鏈。如果任何回調失敗,我需要傳遞一個對象用於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

在這種情況下,你可以提出一個例外,包含需要

舉例而言,所有信息:

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/。 它使用的例子一點點過時扭曲版本,但它仍然是一個方位源開始學習扭曲

+0

外觀極好。工作正常。謝謝@Evgeny Barbashov –

相關問題