All Products
Search
Document Center

Alibaba Cloud SDK:Handle an exception

Last Updated:Jul 29, 2024

This topic describes the exception types in Alibaba Cloud SDK V1.0 for PHP and how to handle an exception.

Exceptions that may occur when you use Alibaba Cloud SDK V1.0 for PHP can be classified into two types: ServerException, which indicates the server exceptions, and ClientException, which indicates the client exceptions. If an exception occurs and the server receives no requests, you cannot obtain the ID of the request that causes the exception. If the server receives the request that causes the exception, you can obtain the request ID. Then, you can use the request ID to contact Alibaba Cloud technical support for help.

Important

In this example, error messages are printed for reference only. In your actual business scenario, handle exceptions with caution and do not ignore exceptions in your project. We recommend that you take reasonable measures to handle exceptions, such as propagating exceptions in a proper manner, recording logs, and performing retries. This helps ensure the robustness and stability of the system.

<?php

require_once 'vendor/autoload.php';

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Ecs\Ecs;

try {
    // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured. 
    AlibabaCloud::accessKeyClient(getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'))->asDefaultClient();
    $request = Ecs::v20140526()->describeRegions();
    $result = $request
        ->version('2014-05-26')
        ->product('Ecs')
        ->action('DescribeRegions')
        ->regionId('cn-hangzhou')
        ->host("ecs.cn-hangzhou.aliyuncs.com")
        ->request();
    print_r($result->toArray());
} catch (ClientException $exception) {
    // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
    echo $exception->getMessage() . PHP_EOL;
} catch (ServerException $exception) {
    // Handle exceptions with caution in your actual business scenario and do not ignore exceptions in your project. In this example, error messages are printed for reference only. 
    echo $exception->getMessage() . PHP_EOL;
    echo $exception->getErrorCode() . PHP_EOL;
    echo $exception->getRequestId() . PHP_EOL;
    echo $exception->getErrorMessage() . PHP_EOL;
}