CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tencentcloud-sdk-python

Comprehensive Python SDK for integrating with Tencent Cloud services, supporting 240+ cloud services with authentication, error handling, and retry mechanisms.

Overview
Eval results
Files

error-handling.mddocs/

Error Handling and Retry

Unified exception handling and configurable retry mechanisms with exponential backoff for robust cloud service integration. The SDK provides comprehensive error information and automatic retry capabilities for transient failures.

Capabilities

TencentCloud SDK Exception

Main exception class providing detailed error information including error codes, messages, and request tracking identifiers for debugging and monitoring.

class TencentCloudSDKException(Exception):
    def __init__(self, code: str = None, message: str = None, requestId: str = None):
        """
        Initialize TencentCloud SDK exception with error details.
        
        Parameters:
        - code (str, optional): Error code from Tencent Cloud API
        - message (str, optional): Human-readable error description
        - requestId (str, optional): Unique request identifier for tracking
        """
    
    def get_code(self) -> str:
        """
        Get the error code.
        
        Returns:
        str: Error code (e.g., "InvalidParameter", "AuthFailure")
        """
    
    def get_message(self) -> str:
        """
        Get the error message.
        
        Returns:
        str: Detailed error description
        """
    
    def get_request_id(self) -> str:
        """
        Get the request ID for tracking.
        
        Returns:
        str: Unique request identifier for support and debugging
        """

Basic Error Handling:

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.cvm.v20170312 import cvm_client, models
from tencentcloud.common import credential

try:
    cred = credential.DefaultCredentialProvider().get_credential()
    client = cvm_client.CvmClient(cred, "ap-shanghai")
    
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    
    print(f"Found {resp.TotalCount} instances")
    
except TencentCloudSDKException as err:
    print(f"TencentCloud API Error:")
    print(f"  Code: {err.get_code()}")
    print(f"  Message: {err.get_message()}")
    print(f"  Request ID: {err.get_request_id()}")
    
except Exception as err:
    print(f"Unexpected error: {err}")

Common Error Codes and Handling:

def handle_tencent_cloud_error(err: TencentCloudSDKException):
    """Handle different types of TencentCloud errors."""
    code = err.get_code()
    message = err.get_message()
    request_id = err.get_request_id()
    
    if code == "AuthFailure":
        print("Authentication failed - check your credentials")
        # Could trigger credential refresh or user notification
        
    elif code == "InvalidParameter":
        print(f"Invalid parameter provided: {message}")
        # Could validate and fix parameters automatically
        
    elif code == "LimitExceeded":
        print("API rate limit exceeded - implementing backoff")
        # Could trigger exponential backoff
        
    elif code == "ResourceNotFound":
        print(f"Resource not found: {message}")
        # Could return empty result or create resource
        
    elif code == "InternalError":
        print("Internal server error - retrying may help")
        # Could trigger automatic retry
        
    else:
        print(f"Unhandled error {code}: {message}")
    
    print(f"Request ID for support: {request_id}")

# Usage
try:
    # API call here
    pass
except TencentCloudSDKException as err:
    handle_tencent_cloud_error(err)

Standard Retry Mechanism

Configurable retry system with exponential backoff, jitter, and logging for handling transient failures automatically.

class StandardRetryer:
    def __init__(self, max_attempts: int = 3, backoff_fn = None, logger = None):
        """
        Initialize standard retry mechanism.
        
        Parameters:
        - max_attempts (int): Maximum retry attempts (default: 3)
        - backoff_fn (callable, optional): Custom backoff function
        - logger (logging.Logger, optional): Logger for retry events
        """
    
    def should_retry(self, exception) -> bool:
        """
        Determine if an exception should trigger a retry.
        
        Parameters:
        - exception: Exception that occurred
        
        Returns:
        bool: True if retry should be attempted
        """
    
    def compute_delay_before_next_retry(self, attempt: int) -> float:
        """
        Calculate delay before next retry attempt.
        
        Parameters:
        - attempt (int): Current attempt number (1-based)
        
        Returns:
        float: Delay in seconds before next attempt
        """

Standard Retry Configuration:

from tencentcloud.common import retry
from tencentcloud.common.profile.client_profile import ClientProfile
import logging
import sys

# Configure retry logger
logger = logging.getLogger("tencentcloud.retry")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stderr))

# Create retry configuration
retryer = retry.StandardRetryer(
    max_attempts=3,  # Try up to 3 times
    logger=logger    # Log retry attempts
)

# Use with client profile
client_profile = ClientProfile()
client_profile.retryer = retryer

client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

# Calls will automatically retry on transient failures
try:
    response = client.DescribeInstances(models.DescribeInstancesRequest())
    print(f"Success after retries: {response.TotalCount} instances")
except TencentCloudSDKException as err:
    print(f"Failed after all retry attempts: {err.get_code()}")

Custom Retry Backoff:

import random
import time

def custom_backoff_function(attempt):
    """Custom exponential backoff with jitter."""
    base_delay = 2 ** attempt  # Exponential: 2, 4, 8, 16 seconds
    jitter = random.uniform(0, 0.1 * base_delay)  # Add 10% jitter
    return base_delay + jitter

# Use custom backoff
retryer = retry.StandardRetryer(
    max_attempts=5,
    backoff_fn=custom_backoff_function,
    logger=logger
)

client_profile = ClientProfile()
client_profile.retryer = retryer

No-Operation Retry

Disabled retry mechanism for scenarios requiring immediate failure feedback or when implementing custom retry logic.

class NoopRetryer:
    def __init__(self):
        """
        Initialize no-operation retryer that never retries.
        """
    
    def should_retry(self, exception) -> bool:
        """
        Always returns False - no retries performed.
        
        Returns:
        bool: Always False
        """
    
    def compute_delay_before_next_retry(self, attempt: int) -> float:
        """
        Returns 0 - no delay since no retries occur.
        
        Returns:
        float: Always 0.0
        """

No-Retry Configuration:

from tencentcloud.common import retry

# Disable automatic retries
no_retry = retry.NoopRetryer()

client_profile = ClientProfile()
client_profile.retryer = no_retry

# Client will fail immediately on any error
client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

Advanced Error Handling Patterns

Retry with Circuit Breaker:

from tencentcloud.common.profile.client_profile import ClientProfile, RegionBreakerProfile
from tencentcloud.common import retry
import logging

# Combine retry logic with circuit breaker
logger = logging.getLogger("tencentcloud")
logger.setLevel(logging.INFO)

# Configure retries
retryer = retry.StandardRetryer(max_attempts=3, logger=logger)

# Configure circuit breaker for region failover
region_breaker = RegionBreakerProfile(
    backup_endpoint="ap-beijing.tencentcloudapi.com",
    max_fail_num=3,
    timeout=30
)

# Combine both mechanisms
client_profile = ClientProfile()
client_profile.retryer = retryer
client_profile.disable_region_breaker = False
client_profile.region_breaker_profile = region_breaker

client = cvm_client.CvmClient(cred, "ap-shanghai", client_profile)

Application-Level Retry Logic:

import time
import random
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

def robust_api_call(client, request, max_retries=3):
    """Application-level retry wrapper with custom logic."""
    
    for attempt in range(max_retries + 1):
        try:
            response = client.DescribeInstances(request)
            return response
            
        except TencentCloudSDKException as err:
            code = err.get_code()
            
            # Don't retry on authentication or parameter errors
            if code in ["AuthFailure", "InvalidParameter", "ResourceNotFound"]:
                raise err
            
            # Don't retry on final attempt
            if attempt == max_retries:
                raise err
            
            # Calculate backoff delay
            delay = (2 ** attempt) + random.uniform(0, 1)
            print(f"Attempt {attempt + 1} failed ({code}), retrying in {delay:.2f}s...")
            time.sleep(delay)

# Usage
try:
    request = models.DescribeInstancesRequest()
    response = robust_api_call(client, request)
    print(f"Success: {response.TotalCount} instances")
except TencentCloudSDKException as err:
    print(f"All attempts failed: {err.get_code()} - {err.get_message()}")

Async Error Handling:

import asyncio
from concurrent.futures import ThreadPoolExecutor
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException

async def async_api_call(client, request):
    """Async wrapper for synchronous SDK calls."""
    loop = asyncio.get_event_loop()
    
    try:
        with ThreadPoolExecutor() as executor:
            response = await loop.run_in_executor(
                executor, 
                client.DescribeInstances, 
                request
            )
        return response
        
    except TencentCloudSDKException as err:
        print(f"Async API error: {err.get_code()}")
        raise

async def parallel_api_calls(clients, request):
    """Make parallel API calls to multiple regions."""
    tasks = [async_api_call(client, request) for client in clients]
    
    try:
        responses = await asyncio.gather(*tasks, return_exceptions=True)
        
        for i, response in enumerate(responses):
            if isinstance(response, TencentCloudSDKException):
                print(f"Region {i} failed: {response.get_code()}")
            else:
                print(f"Region {i}: {response.TotalCount} instances")
                
    except Exception as err:
        print(f"Parallel execution error: {err}")

# Usage
regions = ["ap-shanghai", "ap-beijing", "ap-guangzhou"] 
clients = [cvm_client.CvmClient(cred, region) for region in regions]
request = models.DescribeInstancesRequest()

asyncio.run(parallel_api_calls(clients, request))

Monitoring and Alerting Integration:

import logging
import json
from datetime import datetime

class TencentCloudErrorHandler(logging.Handler):
    """Custom log handler for monitoring TencentCloud errors."""
    
    def emit(self, record):
        if hasattr(record, 'exc_info') and record.exc_info:
            exc_type, exc_value, exc_tb = record.exc_info
            
            if isinstance(exc_value, TencentCloudSDKException):
                error_data = {
                    'timestamp': datetime.utcnow().isoformat(),
                    'error_code': exc_value.get_code(),
                    'error_message': exc_value.get_message(),
                    'request_id': exc_value.get_request_id(),
                    'service': getattr(record, 'service', 'unknown'),
                    'region': getattr(record, 'region', 'unknown')
                }
                
                # Send to monitoring system (implement your own)
                self.send_to_monitoring(error_data)
    
    def send_to_monitoring(self, error_data):
        """Send error data to monitoring system."""
        # Implement integration with your monitoring/alerting system
        print(f"MONITOR: {json.dumps(error_data)}")

# Setup monitoring
monitor_handler = TencentCloudErrorHandler()
logger = logging.getLogger("tencentcloud.errors")
logger.addHandler(monitor_handler)
logger.setLevel(logging.ERROR)

# Use in error handling
try:
    response = client.DescribeInstances(request)
except TencentCloudSDKException as err:
    logger.error("API call failed", exc_info=True, extra={
        'service': 'cvm',
        'region': 'ap-shanghai'
    })
    raise

Install with Tessl CLI

npx tessl i tessl/pypi-tencentcloud-sdk-python

docs

authentication.md

client-infrastructure.md

configuration.md

data-models.md

error-handling.md

index.md

service-clients.md

tile.json