如何处理错误并使其成为结果

How to handle an error and make it a result

我正在查看抖音直播是(正在直播)还是(已结束)

既然TikTok有点难对付,那我就打个招牌,靠一下。

以下代码将采用 TikToker 用户名。如果有直播视频运行,它会显示观看人数,所以我们决定它是(live now)。 否则(例如在下面的代码中),它将被(结束)。就这么简单。

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import ViewerCountUpdateEvent

client: TikTokLiveClient = TikTokLiveClient(unique_id="8_o2o", **({"fetch_room_info_on_connect": True}))


@client.on("viewer_count_update")
async def on_connect(event: ViewerCountUpdateEvent):
    print("Received a new viewer count:", event.viewerCount)


if __name__ == '__main__':
    client.run()

直播结束时,会报错:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\practice\lib\site-packages\TikTokLive\client\base.py", line 216, in _connect
    raise LiveNotFound()
TikTokLive.types.errors.LiveNotFound

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/ahmad/Desktop/ExTrac_Chat_DB/tiktok.py", line 13, in <module>
    client.run()
  File "C:\ProgramData\Anaconda3\envs\practice\lib\site-packages\TikTokLive\client\base.py", line 293, in run
    self.loop.run_until_complete(self._connect())
  File "C:\ProgramData\Anaconda3\envs\practice\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "C:\ProgramData\Anaconda3\envs\practice\lib\site-packages\TikTokLive\client\client.py", line 38, in _connect
    result: str = await super(TikTokLiveClient, self)._connect()
  File "C:\ProgramData\Anaconda3\envs\practice\lib\site-packages\TikTokLive\client\base.py", line 244, in _connect
    raise FailedConnection(message)
TikTokLive.types.errors.FailedConnection

我需要的是处理那个错误。这不是真正的错误,我只是希望它成为我的结果。处理不了

您需要捕获 LiveNotFound 异常并手动处理。您可以将 client.run() 调用包装到 try-except 块中,如下所示:

from TikTokLive import TikTokLiveClient
from TikTokLive.types.events import ViewerCountUpdateEvent
from TikTokLive.types.errors import LiveNotFound

client: TikTokLiveClient = TikTokLiveClient(unique_id="8_o2o", **({"fetch_room_info_on_connect": True}))


@client.on("viewer_count_update")
async def on_connect(event: ViewerCountUpdateEvent):
    print("Received a new viewer count:", event.viewerCount)


if __name__ == '__main__':
    try:
        client.run()
    except LiveNotFound:
        print("The video is no longer live.")

通常,最好至少记录发生的任何异常,以便您了解代码中发生的情况。另请注意,LiveNotFound 异常也可能在其他情况下抛出(例如,如果存在某些连接问题),并且您的代码可能无法区分这些情况。