

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 处理 适用于 PHP 的 Amazon SDK 版本 3 中的错误
处理错误

## 同步处理错误


如果在执行操作时发生错误，将引发异常。因此，如果您需要在代码中处理错误，请围绕您的操作使用 `try`/`catch` 数据块。发生错误时，开发工具包会引发特定于服务的异常。

下面的示例使用了 `Aws\S3\S3Client`。如果发生错误，引发的异常将为 `Aws\S3\Exception\S3Exception` 类型。开发工具包引发的所有特定于服务的异常均是从 `Aws\Exception\AwsException` 类中扩展而来的。这个类中包含有关故障的有用信息，包括请求 ID、错误代码和错误类型。注意：对于某些支持它的服务，响应数据被强制转换为关联数组结构（类似于 `Aws\Result` 对象），可以像普通 PHP 关联数组那样进行访问。`toArray()` 方法返回任意此类数据（如果存在）。

 **导入** 

```
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\Exception\S3Exception;
```

 **示例代码** 

```
// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk([
    'region'   => 'us-west-2'
]);

// Use an Aws\Sdk class to create the S3Client object.
$s3Client = $sdk->createS3();

try {
    $s3Client->createBucket(['Bucket' => 'amzn-s3-demo-bucket']);
} catch (S3Exception $e) {
    // Catch an S3 specific exception.
    echo $e->getMessage();
} catch (AwsException $e) {
    // This catches the more generic AwsException. You can grab information
    // from the exception using methods of the exception object.
    echo $e->getAwsRequestId() . "\n";
    echo $e->getAwsErrorType() . "\n";
    echo $e->getAwsErrorCode() . "\n";

    // This dumps any modeled response data, if supported by the service
    // Specific members can be accessed directly (e.g. $e['MemberName'])
    var_dump($e->toArray());
}
```

## 异步处理错误


在发送异步请求的时候不会引发异常。您必须使用返回的 Promise 的 `then()` 或 `otherwise()` 方法来接收结果或错误。

 **导入** 

```
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\Exception\S3Exception;
```

 **示例代码** 

```
//Asynchronous Error Handling
$promise = $s3Client->createBucketAsync(['Bucket' => 'amzn-s3-demo-bucket']);
$promise->otherwise(function ($reason) {
    var_dump($reason);
});

// This does the same thing as the "otherwise" function.
$promise->then(null, function ($reason) {
    var_dump($reason);
});
```

您可以“解封”Promise，从而引发异常。

 **导入** 

```
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\Exception\S3Exception;
```

 **示例代码** 

```
$promise = $s3Client->createBucketAsync(['Bucket' => 'amzn-s3-demo-bucket']);
```

```
//throw exception
try {
    $result = $promise->wait();
} catch (S3Exception $e) {
    echo $e->getMessage();
}
```