我在一个类中有一个定义,它以我不喜欢的方式处理异常。
类本身位于一个模块中,该模块本身由我导入的模块调用。
我不喜欢的错误处理看起来像这样:
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上托管:
我能做到:
from bitsharesapi import websocket as ws
但我不知道如何处理模块现在它被导入以抢占其异常处理,或者这甚至是接近它的正确方法。
答案 0 :(得分:0)
我在这里解决了我的问题:
chain = Blockchain(bitshares_instance=BitShares(n))
我能够做到:
chain = Blockchain(bitshares_instance=BitShares(n,num_retries=0))
我之前尝试过这个并假设它不起作用:
chain = Blockchain(bitshares_instance=BitShares(n),num_retries=0)
*注意括号放置