【问题标题】:How to catch unhandled error in Deferred originating from threads.deferToThread()如何在 Deferred 中捕获源自threads.deferToThread() 的未处理错误
【发布时间】:2018-09-04 14:30:05
【问题描述】:

我在 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))

在行抛出错误

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

【问题讨论】:

  • 函数可以引发异常(延迟可以触发失败)。你有什么问题?
  • 你好@Jean-PaulCalderone 我收到一个错误“Deferred 中的未处理错误:”并且我的程序崩溃了。我想通过记录一条消息来优雅地处理它(“key_data not found”)而不是“延迟中的未处理错误”

标签: python python-3.x python-2.7 twisted


【解决方案1】:

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

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-handling http://twistedmatrix.com/documents/current/core/howto/threading.html

【讨论】:

  • 非常感谢@notorious.no,它有帮助:)
  • 链接 addcallback 方法对我有用。然而 try..except 方法抛出这个“keysign.discover (DEBUG): Unable to get key_data Unhandled error in Deferred:”
【解决方案2】:

根据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 ... 行替换为:

try:
    key_data = yield threads.deferToThread(self.discovery.find_key, self.userdata)
except SomeExceptionYouCanHandle:
    # Some exception handling code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多