Handle an exception

Updated at:
Copy as MD

Learn the exception types thrown by Alibaba Cloud SDK V2.0 for PHP and how to catch and handle each one.

SDK V2.0 for PHP throws three exception types, each with a different cause and response strategy:

  1. InvalidArgumentException: A required parameter is missing or has an invalid value when you initialize the SDK client. View the exception details in the returned error message.

  2. TeaUnretryableException: A network error persists after all retry attempts are exhausted. Call getLastException to retrieve the request information from the final retry attempt.

  3. TeaError: The API returns a business error. The following properties help diagnose the error:

    1. code: the error code returned by the API.

    2. message: the error message, including the request ID of the failed API call.

    3. data: raw error details returned by the server.

The following example catches the base \Exception class and uses instanceof checks to identify the specific exception type. Check TeaError and TeaUnableRetryError before the generic fallback to handle each type with the appropriate response.

Important

The example prints error messages for reference only. In production, do not silently ignore exceptions. Log them, propagate them to a higher layer, or retry with exponential backoff as appropriate for each exception type.

<?php

require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstancesRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;

class ProxyDemo
{

    public static function main()
    {
        try {
            $config = new Config([
                "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                "endpoint" => "ecs.cn-beijing.aliyuncs.com", // <endpoint>
            ]);
            $client = new Ecs($config);

            $runtime = new RuntimeOptions([]);
            $describeInstancesRequest = new DescribeInstancesRequest([
                "regionId" => "cn-beijing"
            ]);
            $resp = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);
            var_dump($resp);
        } catch (\Exception $error) {
            if ($error instanceof TeaError) {
                // 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. 
                print_r("message:" . $error->getMessage() . "\n");
                print_r("code:" . $error->getCode() . "\n");
                print_r($error->data);
            } elseif ($error instanceof TeaUnableRetryError) {
                // 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. 
                print_r($error->getLastException());
            } else {
                // 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. 
                print_r("message:" . $error->getMessage());
            }
        }
    }
}
ProxyDemo::main();

Response guidance

Choose the appropriate response based on the exception type:

  • InvalidArgumentException: Fix the parameter value before retrying. This error indicates a programming mistake — retrying without a code change will not succeed.

  • TeaUnableRetryError: Retry after a delay. Use exponential backoff to avoid overloading the server. Call getLastException() to log the root cause before retrying.

  • TeaError: Check code and message to determine the cause. API errors such as authentication failures or missing resources require corrective action before retrying.