如何捕获源于线程.deferToThread()

2024-04-18 12:41:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Deferred中得到错误未处理的错误: 有谁能帮忙,怎么处理?在

    @inlineCallbacks
    def start(self):
        # First we try Avahi, if it fails we fallback to Bluetooth because
        # the receiver may be able to use only one of them
        log.info("Trying to use this code with Avahi: %s", self.userdata)
        key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)
        if key_data and not self.stopped:
            success = True
            message = ""
            returnValue((key_data, success, message))
        if self.bt_code and not self.stopped:
            # We try Bluetooth, if we have it
            log.info("Trying to connect to %s with Bluetooth", self.bt_code)
            self.bt = BluetoothReceive(self.bt_port)
            msg_tuple = yield self.bt.find_key(self.bt_code, self.mac)
            key_data, success, message = msg_tuple
            if key_data:
                # If we found the key
            returnValue((key_data, success, message))

错误投球线

^{pr2}$

Tags: tokeyselfmessagedataif错误code
2条回答

对于大多数使用inlineCallbacks的开发人员来说,这是有意义的

try:
    key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)
except Exception as e:
    log.exception('Unable to get key_data')
    returnValue(e)

另一种方法是使用addCallback(成功)和addErrback(失败)链接回调。所以你应该可以这样做:

^{pr2}$

有用的链接

http://twistedmatrix.com/documents/current/core/howto/defer-intro.html#simple-failure-handlinghttp://twistedmatrix.com/documents/current/core/howto/threading.html

根据inlineCallbacks documentation,可以使用try/except语句处理此情况:

例如:

@inlineCallbacks
def getUsers(self):
    try:
        responseBody = yield makeRequest("GET", "/users")
    except ConnectionError:
       log.failure("makeRequest failed due to connection error")
       returnValue([])

    returnValue(json.loads(responseBody))

因此,将key_data = yield ...行替换为:

^{pr2}$

相关问题 更多 >