Handle an exception

更新时间:
复制 MD 格式

Alibaba Cloud SDK V1.0 for PHP throws two exception types: ServerException for server-side errors and ClientException for client-side errors.

Alibaba Cloud SDK V1.0 for PHP raises two exception types: ServerException for server-side errors and ClientException for client-side errors. If the server does not receive the request, no request ID is available. If the server receives the request, you can obtain the request ID from the exception and provide it to Alibaba Cloud technical support for troubleshooting.

Important

The following sample code prints error messages for demonstration purposes only. In production, handle exceptions properly by propagating them, logging errors, and implementing retries to ensure system robustness and stability.

<?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;
}