繁体   English   中英

覆盖导入模块的类函数中的异常处理

[英]override exception handling in class function of imported module

我在类内部有一个定义,该定义以我不喜欢的方式处理异常。

该类本身在模块内部,而该模块本身由我导入的模块调用。

我不喜欢的错误处理如下所示:

class BitSharesWebsocket(Events):

    #[snip]

    def run_forever(self):
        """ This method is used to run the websocket app continuously.
            It will execute callbacks as defined and try to stay
            connected with the provided APIs
        """
        cnt = 0
        while not self.run_event.is_set():
            cnt += 1
            self.url = next(self.urls)
            log.debug("Trying to connect to node %s" % self.url)
            try:
                # websocket.enableTrace(True)
                self.ws = websocket.WebSocketApp(
                    self.url,
                    on_message=self.on_message,
                    on_error=self.on_error,
                    on_close=self.on_close,
                    on_open=self.on_open
                )
                self.ws.run_forever()
            except websocket.WebSocketException as exc:
                if (self.num_retries >= 0 and cnt > self.num_retries):
                    raise NumRetriesReached()

                sleeptime = (cnt - 1) * 2 if cnt < 10 else 10
                if sleeptime:
                    log.warning(
                        "Lost connection to node during wsconnect(): %s (%d/%d) "
                        % (self.url, cnt, self.num_retries) +
                        "Retrying in %d seconds" % sleeptime
                    )
                    time.sleep(sleeptime)

我想在此先占例外:

except websocket.WebSocketException as exc:

并以我自己的方式处理它,即尝试一个新地址,而不是一次又一次尝试相同的地址。

调用时出现此异常:

from bitshares.blockchain import Blockchain
from bitshares import BitShares

try:
    chain = Blockchain(bitshares_instance=BitShares(n))
except:
    print ('hello world')
    pass

当n是错误/无响应的websocket地址时

我从来没有收到“ hello world”消息,因为该模块会先处理异常。

该模块托管在github此处:

https://github.com/xeroc/python-bitshares/blob/9250544ca8eadf66de31c7f38fc37294c11f9548/bitsharesapi/websocket.py

我可以:

from bitsharesapi import websocket as ws

但是我不确定该模块是怎么处理的,因为它已经被导入以抢占其异常处理,或者这是否是正确的处理方法。

我在这里解决了我的问题:

chain = Blockchain(bitshares_instance=BitShares(n))

我能够做到:

chain = Blockchain(bitshares_instance=BitShares(n,num_retries=0))

我以前尝试过此方法,并认为它不起作用:

chain = Blockchain(bitshares_instance=BitShares(n),num_retries=0)

*请注意括号位置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM