如何捕获TikTokLive直播状态检测中的异常并将其转为业务结果
Got it, I totally get what you're going for here—you don't want that messy error trace blowing up your program when a stream ends; instead, you want to flag it as an "ended" status for your business logic. Luckily, Python's exception handling is perfect for this. Let's tweak your code to catch those specific errors and turn them into the result you need.
Here's how to do it:
- Import the specific exceptions that get thrown when a live stream isn't found (since that's what triggers the failed connection when a stream ends).
- Wrap your
client.run()call in atry-exceptblock to catch those exceptions. - Replace the error stack with your business output when the exceptions are caught—just print "ended" or handle it however you need for your workflow.
Updated Full Code:
from TikTokLive import TikTokLiveClient from TikTokLive.types.events import ViewerCountUpdateEvent # Bring in the exceptions we need to catch from TikTokLive.types.errors import LiveNotFound, FailedConnection 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) # Explicitly mark the live status here too, for clarity print("Live status: live now") if __name__ == '__main__': try: client.run() except (LiveNotFound, FailedConnection): # This is where we handle the "stream ended" scenario print("Live status: ended")
Why this works:
When a stream ends, the TikTokLiveClient first throws a LiveNotFound exception, which then propagates into a FailedConnection error. By catching both exceptions, we cover the exact scenario where the stream is no longer active. Instead of letting the program crash with a trace, we just output your desired "ended" status—exactly the business logic you want.
You can easily extend this too: instead of just printing, you could store the status in a variable, trigger another function, or log it to a database—whatever fits your use case.
内容的提问来源于stack exchange,提问作者user18532875

