CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-aliyun-python-sdk-core

The core module of Aliyun Python SDK providing authentication, request handling, and API communication for Alibaba Cloud services.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

exception-handling.mddocs/

Exception Handling

Comprehensive exception classes for handling both client-side and server-side errors with detailed error information and debugging capabilities. The SDK provides structured error handling to help developers identify and resolve issues quickly.

Capabilities

Client Exception

Client-side exceptions for SDK-related errors including invalid parameters, network issues, and authentication problems.

class ClientException(Exception):
    def __init__(self, code, msg):
        """
        Initialize client exception for SDK-side errors.
        
        Parameters:
        - code (str): Error code identifying the specific error type
        - msg (str): Human-readable error message
        """
    
    def get_error_code(self):
        """
        Get the error code for this exception.
        
        Returns:
        str: Error code identifying the error type
        """
    
    def get_error_msg(self):
        """
        Get the error message for this exception.
        
        Returns:
        str: Human-readable error message
        """
    
    def get_error_type(self):
        """
        Get the error type (always "Client" for ClientException).
        
        Returns:
        str: Error type identifier
        """

Server Exception

Server-side exceptions for API errors returned by Alibaba Cloud services, including service errors and request validation failures.

class ServerException(Exception):
    def __init__(self, code, msg, http_status=None, request_id=None):
        """
        Initialize server exception for API-side errors.
        
        Parameters:
        - code (str): Error code from the API response
        - msg (str): Error message from the API response
        - http_status (int, optional): HTTP status code of the response
        - request_id (str, optional): Request ID for debugging and support
        """
    
    def get_error_code(self):
        """
        Get the API error code.
        
        Returns:
        str: API error code from the service response
        """
    
    def get_error_msg(self):
        """
        Get the API error message.
        
        Returns:
        str: Error message from the service response
        """
    
    def get_error_type(self):
        """
        Get the error type (always "Server" for ServerException).
        
        Returns:
        str: Error type identifier
        """
    
    def get_http_status(self):
        """
        Get the HTTP status code of the failed request.
        
        Returns:
        int: HTTP status code (e.g., 400, 403, 500)
        """
    
    def get_request_id(self):
        """
        Get the request ID for debugging purposes.
        
        Returns:
        str: Unique request identifier for support and debugging
        """

Error Types

Constants defining different categories of errors for classification purposes.

from aliyunsdkcore.acs_exception import error_type

ERROR_TYPE_CLIENT: str  # "Client"
ERROR_TYPE_SERVER: str  # "Server"

Error Codes

Common error codes that may be encountered when using the SDK.

from aliyunsdkcore.acs_exception import error_code

# Client error codes
SDK_INVALID_PARAMS: str
SDK_INVALID_REQUEST: str
SDK_INVALID_CREDENTIAL: str
SDK_NETWORK_ERROR: str
SDK_TIMEOUT_ERROR: str
SDK_HTTP_ERROR: str

# Server error codes (examples - actual codes vary by service)
INVALID_ACCESS_KEY_ID: str
SIGNATURE_DOES_NOT_MATCH: str
INVALID_PARAMETER: str
MISSING_PARAMETER: str
THROTTLING: str
INTERNAL_ERROR: str

Error Messages

Predefined error messages for common error scenarios.

from aliyunsdkcore.acs_exception import error_msg

# Get error message by code
def get_msg(error_code):
    """
    Get predefined error message for a given error code.
    
    Parameters:
    - error_code (str): Error code
    
    Returns:
    str: Corresponding error message or generic message if not found
    """

Usage Examples

Basic Exception Handling

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

try:
    # Create and execute request
    client = AcsClient(ak="your-ak", secret="your-secret")
    request = CommonRequest()
    request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
    request.set_version("2014-05-26")
    request.set_action_name("DescribeInstances")
    request.set_method("POST")
    
    response = client.do_action_with_exception(request)
    print("Request successful:", response.decode('utf-8'))
    
except ClientException as e:
    print(f"Client Error: {e.get_error_code()} - {e.get_error_msg()}")
    print(f"Error Type: {e.get_error_type()}")
    
except ServerException as e:
    print(f"Server Error: {e.get_error_code()} - {e.get_error_msg()}")
    print(f"HTTP Status: {e.get_http_status()}")
    print(f"Request ID: {e.get_request_id()}")
    print(f"Error Type: {e.get_error_type()}")

Specific Error Code Handling

from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

try:
    response = client.do_action_with_exception(request)
    
except ClientException as e:
    error_code = e.get_error_code()
    
    if error_code == "SDK.InvalidCredential":
        print("Invalid credentials - check your access key and secret")
    elif error_code == "SDK.NetworkError":
        print("Network connectivity issue - check your internet connection")
    elif error_code == "SDK.TimeoutError":
        print("Request timed out - try increasing timeout or retry")
    else:
        print(f"Unexpected client error: {error_code} - {e.get_error_msg()}")
        
except ServerException as e:
    error_code = e.get_error_code()
    
    if error_code == "InvalidAccessKeyId.NotFound":
        print("Access Key ID not found - verify your credentials")
    elif error_code == "SignatureDoesNotMatch":
        print("Signature mismatch - check your access key secret")
    elif error_code == "Throttling":
        print("Request throttled - implement exponential backoff")
        print(f"Request ID for support: {e.get_request_id()}")
    elif error_code == "InternalError":
        print("Service internal error - contact support")
        print(f"Request ID: {e.get_request_id()}")
    else:
        print(f"API error: {error_code} - {e.get_error_msg()}")
        print(f"Request ID: {e.get_request_id()}")

Retry Logic with Exception Handling

import time
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

def make_request_with_retry(client, request, max_retries=3):
    """Execute request with retry logic for transient errors."""
    
    for attempt in range(max_retries + 1):
        try:
            response = client.do_action_with_exception(request)
            return response.decode('utf-8')
            
        except ClientException as e:
            if attempt == max_retries:
                raise  # Re-raise on final attempt
                
            error_code = e.get_error_code()
            if error_code in ["SDK.NetworkError", "SDK.TimeoutError"]:
                print(f"Retrying after client error: {error_code}")
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise  # Don't retry non-transient client errors
                
        except ServerException as e:
            if attempt == max_retries:
                raise  # Re-raise on final attempt
                
            error_code = e.get_error_code()
            http_status = e.get_http_status()
            
            # Retry on throttling and 5xx server errors
            if error_code == "Throttling" or (http_status and http_status >= 500):
                print(f"Retrying after server error: {error_code}")
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise  # Don't retry 4xx client errors

# Usage
try:
    result = make_request_with_retry(client, request)
    print("Success:", result)
except (ClientException, ServerException) as e:
    print(f"Failed after retries: {e.get_error_code()} - {e.get_error_msg()}")

Error Logging and Debugging

import logging
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def execute_with_logging(client, request):
    """Execute request with comprehensive error logging."""
    
    try:
        logger.info("Executing API request...")
        response = client.do_action_with_exception(request)
        logger.info("Request completed successfully")
        return response.decode('utf-8')
        
    except ClientException as e:
        logger.error(
            "Client exception occurred: code=%s, message=%s, type=%s",
            e.get_error_code(),
            e.get_error_msg(),
            e.get_error_type()
        )
        raise
        
    except ServerException as e:
        logger.error(
            "Server exception occurred: code=%s, message=%s, status=%s, request_id=%s",
            e.get_error_code(),
            e.get_error_msg(),
            e.get_http_status(),
            e.get_request_id()
        )
        raise

Custom Exception Handling

class CustomAPIError(Exception):
    """Custom exception for application-specific error handling."""
    
    def __init__(self, message, error_code=None, request_id=None):
        super().__init__(message)
        self.error_code = error_code
        self.request_id = request_id

def safe_api_call(client, request):
    """Wrapper that converts SDK exceptions to custom exceptions."""
    
    try:
        response = client.do_action_with_exception(request)
        return response.decode('utf-8')
        
    except ClientException as e:
        raise CustomAPIError(
            f"SDK client error: {e.get_error_msg()}",
            error_code=e.get_error_code()
        )
        
    except ServerException as e:
        raise CustomAPIError(
            f"API server error: {e.get_error_msg()}",
            error_code=e.get_error_code(),
            request_id=e.get_request_id()
        )

# Usage
try:
    result = safe_api_call(client, request)
    print("Success:", result)
except CustomAPIError as e:
    print(f"Application error: {e}")
    if e.request_id:
        print(f"Request ID: {e.request_id}")

Common Error Scenarios

Authentication Errors

  • InvalidAccessKeyId.NotFound: Access key ID doesn't exist
  • SignatureDoesNotMatch: Incorrect access key secret or signature computation
  • InvalidSecurityToken.Expired: STS token has expired
  • InvalidSecurityToken.Malformed: Malformed STS token

Request Errors

  • MissingParameter: Required parameter not provided
  • InvalidParameter: Parameter value is invalid
  • Throttling: Too many requests, rate limiting applied
  • RequestTimeTooSkewed: Client clock is not synchronized

Network Errors

  • SDK.NetworkError: Network connectivity issues
  • SDK.TimeoutError: Request timeout exceeded
  • SDK.HttpError: HTTP-level errors (DNS resolution, connection failures)

Install with Tessl CLI

npx tessl i tessl/pypi-aliyun-python-sdk-core

docs

authentication.md

client-management.md

exception-handling.md

index.md

request-types.md

retry-backoff.md

tile.json