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



我正在检查TikTok直播视频是(现在直播)还是(结束)。

因为TikTok有点难处理,所以我会做一个标志,依靠它。

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

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:ProgramDataAnaconda3envspracticelibsite-packagesTikTokLiveclientbase.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:ProgramDataAnaconda3envspracticelibsite-packagesTikTokLiveclientbase.py", line 293, in run
self.loop.run_until_complete(self._connect())
File "C:ProgramDataAnaconda3envspracticelibasynciobase_events.py", line 616, in run_until_complete
return future.result()
File "C:ProgramDataAnaconda3envspracticelibsite-packagesTikTokLiveclientclient.py", line 38, in _connect
result: str = await super(TikTokLiveClient, self)._connect()
File "C:ProgramDataAnaconda3envspracticelibsite-packagesTikTokLiveclientbase.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异常也可能在其他情况下抛出(例如,如果有一些连接问题),并且您的代码可能无法区分这些情况。

相关内容

  • 没有找到相关文章

最新更新