亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何捕獲gen.Task內部的異常?

如何捕獲gen.Task內部的異常?

溫溫醬 2023-07-18 15:39:45
我使用的是python 2.7,龍卷風4.5以下代碼不起作用: except 塊不會被觸發。我不明白為什么?@gen.coroutinedef co_do_thing():  yield gen.Task(do_thing)def do_thing(callback):  try:    a, b = ...    result = maybe_throw(a, b, callback)  except Exception as e:    # this block is not called    if a:      raise ApiError("called with A")    elif b:      raise ApiError("called with B")    else:      raise edef maybe_throw(arg1, arg2, callback):  if random.random() < 0.5:    raise AssertionError("yikes")  callback("done")co_do_thing相反,我可以在調用周圍捕獲異常gen.Task;但后來我不知道我如何調用的上下文maybe_throw。maybe_throw就我而言,引發較低級別的異常并讓調用者根據輸入將其轉換為人類可讀的錯誤更有意義。我是否只需要重構它以在較低級別調用 gen.Task ?那會很煩人:/
查看完整描述

1 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

當我測試它似乎有效時,會引發異常。下面是簡單的測試套件:


import q  # q.py is the file with question's code


import unittest

from mock import patch, Mock

from tornado.testing import gen_test, AsyncTestCase



class MyTest(AsyncTestCase):


    def setUp(self):

        self.mock_random = patch('q.random').start()

        AsyncTestCase.setUp(self)


    def tearDown(self):

        AsyncTestCase.tearDown(self)

        patch.stopall()


    @gen_test

    def test_no_error(self):

        self.mock_random.return_value = 0.7

        res = yield q.co_do_thing()

        self.assertEqual(res, 'done')


    @gen_test

    def test_exception(self):

        self.mock_random.return_value = 0.1

        with self.assertRaises(Exception) as ctx:

            yield q.co_do_thing()

        self.assertEqual(ctx.exception.message, 'called with A')



if __name__ == '__main__':

    unittest.main()

測試通過了:


..

----------------------------------------------------------------------

Ran 2 tests in 0.002s


OK

這是q.py,我添加了 return 語句來測試它。


from random import random

from tornado import gen


@gen.coroutine

def co_do_thing():

    res = yield gen.Task(do_thing)

    # added: to enable to test it meaningfully

    raise gen.Return(res)


def do_thing(callback):

    try:

        a, b = 22, 33

        result = maybe_throw(a, b, callback)

    except Exception as e:

        if a:

            raise Exception("called with A")

        elif b:

            raise Exception("called with B")

        else:

            raise e


def maybe_throw(arg1, arg2, callback):

    if random() < 0.5:

        raise AssertionError("yikes")

    callback("done")


查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號