Exception handling

更新时间:
复制 MD 格式

When you use Simple Log Service SDK to send API requests, exceptions may occur due to network interruptions or latency. This topic describes how the SDK handles these exceptions and how to implement retry logic.

Exception types and handling mechanism

SDK exceptions fall into the following types:

  • Exceptions returned by Simple Log Service. The SDK handles these exceptions. For more information, see the API operation descriptions and Error codes.

  • Network exceptions that occur when the SDK sends requests, such as network disconnection and server response timeout.

  • Platform- and language-specific exceptions generated by the SDK, such as memory overflow.

The SDK for each programming language throws exceptions as follows:

  • Server-returned exceptions and network exceptions are packaged in the LogException class and thrown by the SDK.

  • Platform- and language-specific exceptions are not handled by the SDK. They are packaged in the Native Exception class of the corresponding platform and language and thrown directly.

LogException

The LogException class is defined by the SDK to handle Simple Log Service logic-related exceptions. It inherits the base exception class in each programming language and provides the following information:

  • Error code: the exception type. For server-returned exceptions, this matches the API error code. For network exceptions, the error code is RequestError. For more information, see API Reference.

  • Error message: a description of the exception. For server-returned exceptions, this matches the API error message. For network exceptions, the error message is request is failed. For more information, see API Reference.

  • Request ID: the ID of the request that triggered the exception. This ID is generated by Simple Log Service and is valid only when the server returns an error. Otherwise, it is an empty string. You can provide this ID to the Simple Log Service team for troubleshooting.

Request failures and retries

When you use Simple Log Service SDK, requests may fail due to temporary network disconnection, transmission latency, or slow server response. The SDK throws exceptions directly without implementing retry logic. You must implement custom handling, such as retrying the request or throwing an exception.

Examples

The following examples show how to handle network exceptions with retry logic when you access a project named big-game in the China (Hangzhou) region:

// Other code. 
// Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");   
String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); 
String project = "big-game";
String endpoint = "cn-hangzhou.sls.aliyuncs.com";
int max_retries = 3;
/*
 * Create a client. 
 */
Client client = new Client(accessId, accessKey, endpoint);
ListLogStoresRequest lsRequest = new ListLogStoresRequest(project);
for (int i = 0; i < max_retries; i++)
{
    try
    {
        ListLogStoresResponse res = client.ListLogStores(lsRequest);
        // Process the returned response. 
        break;
    }
    catch(LogException e)
    {
        if (e.GetErrorCode() == "RequestError")
        {
            if ( i == max_retries - 1)
            {
                System.out.println("request is still failed after all retries.");
                break;
            }
            else
                System.out.println("request error happens, retry it!");
        }
        else
        {
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            System.out.println("error requestId :" + e.GetRequestId());
            break;
        }
    }
    catch(Exception ex)
    {
        System.out.println("unrecoverable exception when listing logstores.");
        break;
    }
}
// Other code.
// Other code. 
// Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
String accessId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");     
String accessKey = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");    
String project = "big-game";
String endpoint = "cn-hangzhou.sls.aliyuncs.com";
int max_retries = 3;
// Create a client. 
SLSClient client = new SLSClient(endpoint, accessId, accessKey);
ListLogstoresRequest request = new ListLogstoresRequest();
request.Project = project;
for (int i = 0; i < max_retries; i++)
{
    try
    {
        ListLogstoresResponse response = client.ListLogstores(request);
        // Process the returned response. 
        break;
    }
    catch(LogException e)
    {
        if (e.errorCode == "SLSRequestError")
        {
            if ( i == max_retries - 1)
            {
                Console.Writeline("request is still failed after all retries.");
                break;
            }
            else
            {
                Console.Writeline("request error happens, retry it!");
            }
        }
        else
        {
            Console.Writeline("error code :" + e.errorCode);
            Console.Writeline("error message :" + e.Message);
            Console.Writeline("error requestId :" + e.RequestId);
            break;
        }
    }
    catch(Exception ex)
    {
        Console.Writeline("unrecoverable exception when listing logstores.");
        break;
    }
}
// Other code.
<?php
// Other code. 
$endpoint = 'cn-hangzhou.sls.aliyuncs.com';
// Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
$accessId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'); 
$accessKey = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); 
$maxRetries = 3;
// Create a client. 
$client = new Aliyun_Sls_Client($endpoint, $accessId, $accessKey);
$project = 'big-game';
$request = new Aliyun_Sls_Models_ListLogstoresRequest($project);
for($i = 0; $i < $maxRetries; ++$i)
{
    try
    {
        $response = $client->ListLogstores($request);
        // Process the returned response. 
        break;
    }
    catch (Aliyun_Sls_Exception $e)
    {
        if ($e->getErrorCode()=='RequestError')
        {
            if ($i+1 == $maxRetries)
            {
                echo "error code :" . $e->getErrorCode() . PHP_EOL;
                echo "error message :" . $e->getErrorMessage() . PHP_EOL;
                break;
            }
            echo 'request error happens, retry it!' . PHP_EOL;
        }
        else
        {
            echo "error code :" . $e->getErrorCode() . PHP_EOL;
            echo "error message :" . $e->getErrorMessage() . PHP_EOL;
            echo "error requestId :" . $e->getRequestId() . PHP_EOL;
            break;
        }
    }
    catch (Exception $ex)
    {
        echo 'unrecoverable exception when listing logstores.' . PHP_EOL;
        var_dump($ex);
        break;
    }
}
// Other code.
from aliyun.log import LogClient, ListLogstoresRequest, LogException;

# Other code. 
from aliyun.log.logclient import xrange

endpoint = 'cn-hangzhou.log.aliyuncs.com'
# Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
accessId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey =  os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
maxRetries = 3
# Create a client. 
client = LogClient(endpoint, accessId, accessKey)
project = 'big-game'
lsRequest = ListLogstoresRequest(project)
for i in xrange(maxRetries):
    try:
        res = client.ListLogstores(lsRequest)
        # Process the returned response. 
        break
    except LogException as e:
        if e.get_error_code() == "RequestError":
            if i+1 == maxRetries:
                print("error code :" + e.get_error_code())
                print("error message :" + e.get_error_message())
                break
            else:
                print("request error happens, retry it!")
        else:
            print("error code :" + e.get_error_code())
            print("error message :" + e.get_error_message())
            print("error requestId :" + e.get_request_id())
            break
    except Exception as ex:
        print("unrecoverable exception when listing logstores.")
        break
# Other code.