簡體   English   中英

Python。 異步函數引發異常並且 try catch 無助於捕獲它

[英]Python. Asynchronous function raises exception and try catch doesn't help to catch it

我正在做與 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)

我試圖捕捉異常以繼續程序,但它得到異常並停止工作。

except子句中raise exc重新引發異常。 你的意思是要包括它嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM