處理第 3 適用於 PHP 的 AWS SDK 版中的錯誤 - 適用於 PHP 的 AWS SDK

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

處理第 3 適用於 PHP 的 AWS SDK 版中的錯誤

同步錯誤處理

執行操作時若發生錯誤,將顯示例外情況。因此,如果您需要處理程式碼中的錯誤,請在操作周圍使用 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' => 'my-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()); }

非同步錯誤處理

傳送非同步請求時不會丟出例外狀況。但是,您必須使用傳回承諾的 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' => 'my-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' => 'my-bucket']);
//throw exception try { $result = $promise->wait(); } catch (S3Exception $e) { echo $e->getMessage(); }