我正在做与Bitmax市场合作的机器人。这是Bot的课程。它通过websocket和REST连接到Bitmax,并且还为Web客户端提供了REST服务器。
class MarketBot:
async def handle_data(self):
@self.ws.add_dispatcher(name='receiver')
async def handler(msg):
if msg['m'] == 'order':
try:
order_id = msg['data']['orderId']
status = msg['data']['st']
if status in ('Filled', 'PartiallyFilled'):
raw = f'Ордер на бирже Bitmax сработал'
if self.sms_on:
await self.sms.send_sms([self.sms_phone], raw)
elif status != 'New':
self._logger.info(status)
except Exception as exc:
self._logger.exception(exc)
raise exc
while True:
try:
await self.ws.handle_messages(close_exc=False)
except self.ws.WSClosed as exc:
await self.ws.__aenter__()
continue
return result
async def bot(self):
try:
await self.subscribe_to_channel(
f'order:cash', id='abc')
self.tasks = asyncio.gather(
self.handle_data(),
self.handle_rate(),
self.send_from_queue(),
)
await self.tasks
except asyncio.CancelledError:
return None
这是使用WebSocket连接的类
class BitmaxWebSocket:
async def dispatch(self, message):
if message.type in (
aiohttp.WSMsgType.CLOSE,
aiohttp.WSMsgType.CLOSED,
aiohttp.WSMsgType.CLOSING,
):
exc = self.WSClosed(f'Dispatch: WebSocket apparently closed\n{message}')
self._logger.error(message)
raise exc
elif message.type != aiohttp.WSMsgType.TEXT:
exc = ValueError(f'Non-text message\n{message}')
self._logger.exception(exc)
raise exc
try:
data = message.json()
if data['m'] == 'ping':
if int(data['hp']) < 3:
self._logger.warning(data)
await self.send_json(op='pong', data={})
else:
for dispatcher in self._dispatchers:
asyncio.create_task(dispatcher.func(data))
except ValueError as exc:
self._logger.exception(exc)
raise exc
async def handle_messages(self, close_exc=True):
while True:
try:
if self.is_closed():
raise self.WSClosed('Handling: WebSocket apparently closed')
message = await self._ws_connection.receive()
message = await self.dispatch(message)
except self.WSClosed as exc:
self._logger.exception(exc)
if close_exc:
raise exc
await self.__aenter__()
continue
except Exception as exc:
self._logger.exception(exc)
raise exc
它会引发此错误,但不会继续起作用。
[13:56:58 22.10.2020] level=ERROR Dispatch: WebSocket apparently closed
WSMessage(type=<WSMsgType.CLOSING: 256>, data=None, extra=None)
Traceback (most recent call last):
File "/home/market-bot/market-bot/bitmax-bot/api/bitmax_api.py", line 225, in handle_messages
message = await self.dispatch(message)
File "/home/market-bot/market-bot/bitmax-bot/api/bitmax_api.py", line 201, in dispatch
raise exc
api.bitmax_api.BitmaxWebSocket.WSClosed: Dispatch: WebSocket apparently closed
WSMessage(type=<WSMsgType.CLOSING: 256>, data=None, extra=None)
我正在尝试捕获异常以继续执行该程序,但是该程序获取异常并停止工作。
答案 0 :(得分:0)
raise exc
子句中的 except
重新引发该异常。您是要包含它吗?