Skip to main content

Overview

TikTokLive provides a comprehensive set of exception classes to help you handle various error scenarios. All errors inherit from the base TikTokLiveError class.

Base Error Class

TikTokLiveError

The base exception class for all TikTokLive errors. All error messages are automatically prefixed with the package version.
from TikTokLive.client.errors import TikTokLiveError

try:
    # Your code here
    pass
except TikTokLiveError as e:
    print(f"TikTokLive error occurred: {e}")

Connection Errors

AlreadyConnectedError

Thrown when attempting to connect to a stream that the client is already connected to.
from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import AlreadyConnectedError

client = TikTokLiveClient(unique_id="@username")

try:
    await client.connect()
    await client.connect()  # This will raise AlreadyConnectedError
except AlreadyConnectedError:
    print("Already connected to this stream!")

UserOfflineError

Thrown when the requested streamer is not currently live.
from TikTokLive.client.errors import UserOfflineError

try:
    await client.connect()
except UserOfflineError:
    print("This user is not currently live")

UserNotFoundError

Thrown when a user cannot be found or does not have a livestream account. This typically occurs for accounts with fewer than 1,000 followers.
from TikTokLive.client.errors import UserNotFoundError

try:
    await client.connect()
except UserNotFoundError as e:
    print(f"User '{e.unique_id}' not found or doesn't have livestream access")
Attributes:
  • unique_id (str): The username that was not found

AgeRestrictedError

Thrown when attempting to connect to an age-restricted stream without providing a session ID.
from TikTokLive.client.errors import AgeRestrictedError

try:
    await client.connect()
except AgeRestrictedError:
    print("This stream is age-restricted. Pass sessionid to bypass.")
    # Reconnect with session ID
    client = TikTokLiveClient(
        unique_id="@username",
        sessionid="your_session_id"
    )
To access age-restricted streams, you need to provide a valid TikTok session ID. See the Authentication guide for details.

Blocking Errors

These errors indicate that TikTok has detected or blocked your connection attempt.

InitialCursorMissingError

Thrown when the cursor required for connecting to TikTok is missing, indicating a potential block.
from TikTokLive.client.errors import InitialCursorMissingError

try:
    await client.connect()
except InitialCursorMissingError:
    print("Connection blocked: cursor missing")

WebsocketURLMissingError

Thrown when the WebSocket URL to connect to TikTok is missing, indicating a potential block.
from TikTokLive.client.errors import WebsocketURLMissingError

try:
    await client.connect()
except WebsocketURLMissingError:
    print("Connection blocked: WebSocket URL missing")

WebcastBlocked200Error

Thrown when the webcast is blocked by TikTok with a 200 status code, indicating detection.
from TikTokLive.client.errors import WebcastBlocked200Error

try:
    await client.connect()
except WebcastBlocked200Error:
    print("Connection detected and blocked by TikTok")

Sign API Errors

Errors related to the signing API used for request authentication.

SignAPIError

Base class for all Sign API related errors. Contains detailed error information.
from TikTokLive.client.errors import SignAPIError

try:
    await client.connect()
except SignAPIError as e:
    print(f"Sign API error: {e.reason.name}")
    if e.response:
        print(f"Log ID: {e.log_id}")
        print(f"Agent ID: {e.agent_id}")
Attributes:
  • reason (ErrorReason): Enum indicating the specific failure reason
  • response (Optional[httpx.Response]): The HTTP response object if available
  • log_id (Optional[str]): Request log ID for debugging
  • agent_id (Optional[str]): Agent ID from the response
Error Reasons:
  • RATE_LIMIT: Rate limit exceeded
  • CONNECT_ERROR: Connection error
  • EMPTY_PAYLOAD: Empty response payload
  • SIGN_NOT_200: Non-200 status code
  • EMPTY_COOKIES: Missing required cookies
  • PREMIUM_ENDPOINT: Premium endpoint access required
  • AUTHENTICATED_WS: Attempting authenticated WebSocket connection

SignatureRateLimitError

Thrown when you exceed the Sign API rate limit.
from TikTokLive.client.errors import SignatureRateLimitError
import asyncio

try:
    await client.connect()
except SignatureRateLimitError as e:
    retry_seconds = e.retry_after
    print(f"Rate limited. Retry after {retry_seconds} seconds")
    print(f"Reset time: {e.reset_time}")
    await asyncio.sleep(retry_seconds)
Attributes:
  • retry_after (int): Seconds to wait before retrying
  • reset_time (int): Unix timestamp when the limit resets

UnexpectedSignatureError

Thrown when the Sign API returns an unexpected non-200 status code.
from TikTokLive.client.errors import UnexpectedSignatureError

try:
    await client.connect()
except UnexpectedSignatureError:
    print("Unexpected signature response")

SignatureMissingTokensError

Thrown when the Sign API returns an empty payload without required tokens.
from TikTokLive.client.errors import SignatureMissingTokensError

try:
    await client.connect()
except SignatureMissingTokensError:
    print("Missing authentication tokens in signature")

PremiumEndpointError

Thrown when attempting to access a premium endpoint without proper authorization.
from TikTokLive.client.errors import PremiumEndpointError

try:
    await client.connect()
except PremiumEndpointError as e:
    print(f"Premium endpoint error: {e}")

AuthenticatedWebSocketConnectionError

Thrown when sending a session ID to the sign server, which is considered risky and could lead to account bans.
from TikTokLive.client.errors import AuthenticatedWebSocketConnectionError

try:
    await client.connect()
except AuthenticatedWebSocketConnectionError:
    print("Authenticated WebSocket connection blocked for safety")
Sending session IDs to the sign server is disabled by default to protect your account from potential bans.

Comprehensive Error Handling Example

from TikTokLive import TikTokLiveClient
from TikTokLive.client.errors import (
    AlreadyConnectedError,
    UserOfflineError,
    UserNotFoundError,
    AgeRestrictedError,
    SignatureRateLimitError,
    SignAPIError,
    TikTokLiveError
)
import asyncio

async def connect_with_retry(username: str, max_retries: int = 3):
    client = TikTokLiveClient(unique_id=username)
    
    for attempt in range(max_retries):
        try:
            await client.connect()
            print("Connected successfully!")
            return client
            
        except AlreadyConnectedError:
            print("Already connected")
            return client
            
        except UserOfflineError:
            print(f"{username} is not live. Waiting...")
            await asyncio.sleep(60)
            
        except UserNotFoundError as e:
            print(f"User '{e.unique_id}' not found")
            return None
            
        except AgeRestrictedError:
            print("Age-restricted stream. Add sessionid to access.")
            return None
            
        except SignatureRateLimitError as e:
            print(f"Rate limited. Waiting {e.retry_after}s...")
            await asyncio.sleep(e.retry_after)
            
        except SignAPIError as e:
            print(f"Sign API error: {e.reason.name}")
            if e.log_id:
                print(f"Log ID: {e.log_id}")
            await asyncio.sleep(5)
            
        except TikTokLiveError as e:
            print(f"TikTokLive error: {e}")
            await asyncio.sleep(5)
            
        except Exception as e:
            print(f"Unexpected error: {e}")
            await asyncio.sleep(5)
    
    print(f"Failed to connect after {max_retries} attempts")
    return None

if __name__ == '__main__':
    asyncio.run(connect_with_retry("@username"))

Best Practices

Catch Specific Errors

Always catch specific error types before the general TikTokLiveError to handle different scenarios appropriately.

Implement Retry Logic

Use exponential backoff for retries, especially for rate limit and connection errors.

Log Error Details

For Sign API errors, log the log_id and agent_id for debugging.

Handle User State

Gracefully handle offline users and user not found errors with appropriate user feedback.

Build docs developers (and LLMs) love