如何在源自threads.deferToThread()的Deferred中捕获未处理的错误 [英] How to catch unhandled error in Deferred originating from threads.deferToThread()

查看:49
本文介绍了如何在源自threads.deferToThread()的Deferred中捕获未处理的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在延迟中收到错误未处理的错误:任何人都可以帮忙,如何处理?

I'm getting the error Unhandled error in Deferred: Can anybody help, how to handle this?

    @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))

在行处抛出错误

key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)

推荐答案

对于大多数使用 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(失败)链接回调.所以你应该能够做这样的事情:

Another way would be to chain callback using addCallback (success) and addErrback (failure). So you should be able to do something like this:

d = threads.deferToThread(self.discovery.find_key, self.userdata)    # notice there's no yield
d.addCallback(success_callback)
d.addErrback(failure_callback)
key_data = yield d

有用的链接

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

这篇关于如何在源自threads.deferToThread()的Deferred中捕获未处理的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆