

終止支援通知： 將於 2026 AWS 年 5 月 20 日結束對 的支援 AWS SimSpace Weaver。2026 年 5 月 20 日之後，您將無法再存取 SimSpace Weaver 主控台或 SimSpace Weaver 資源。如需詳細資訊，請參閱[AWS SimSpace Weaver 終止支援](https://docs.aws.amazon.com/simspaceweaver/latest/userguide/simspaceweaver-end-of-support.html)。

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

# Result 和錯誤處理
<a name="working-with_app-sdk_result"></a>

`Aws::WeaverRuntime::Result<T>` 類別使用第三方`Outcome`程式庫。您可以使用下列模式來檢查 API 呼叫傳回的 `Result`和 擷取錯誤。

```
void DoBeginUpdate(Application& app)
{
    Result<Transaction> transactionResult = Api::BeginUpdate(app);
    
    if (transactionResult)
    {
        Transaction transaction = 
            std::move(transactionResult).assume_value();
        
        /**
         * Do things with transaction ...
         */
    }
    else
    {     
        ErrorCode errorCode = WEAVERRUNTIME_EXPECT_ERROR(transactionResult);
        /**
         * Macro compiles to:
         * ErrorCode errorCode = transactionResult.assume_error();
         */
    }
}
```

## Result 控制陳述式巨集
<a name="working-with_app-sdk_result_macro"></a>

在傳回類型為 的函數內`Aws::WeaverRuntime::Result<T>`，您可以使用`WEAVERRUNTIME_TRY`巨集，而不是先前的程式碼模式。巨集將執行傳遞給它的函數。如果傳遞的函數失敗，巨集會讓封裝函數傳回錯誤。如果傳遞的函數成功，則執行會繼續進行到下一行。下列範例顯示先前`DoBeginUpdate()`函數的重寫。此版本使用`WEAVERRUNTIME_TRY`巨集，而非if-else控制項結構。請注意，函數的傳回類型為 `Aws::WeaverRuntime::Result<void>`。

```
Aws::WeaverRuntime::Result<void> DoBeginUpdate(Application& app)
{
    /**
     * Execute Api::BeginUpdate() 
     * and return from DoBeginUpdate() if BeginUpdate() fails.
     * The error is available as part of the Result.
     */
    WEAVERRUNTIME_TRY(Transaction transaction, Api::BeginUpdate(m_app));
    
    /**
     * Api::BeginUpdate executed successfully.
     *
     * Do things here.
     */
    
    return Aws::Success();
}
```

如果`BeginUpdate()`失敗，則巨集會提早`DoBeginUpdate()`傳回失敗。您可以使用 `WEAVERRUNTIME_EXPECT_ERROR`巨集從 取得 `Aws::WeaverRuntime::ErrorCode` `BeginUpdate()`。下列範例顯示 `Update()`函數如何在失敗時呼叫 `DoBeginUpdate()` 並取得錯誤代碼。

```
void Update(Application& app)
{
    Result<void> doBeginUpdateResult = DoBeginUpdate(app);
    
    if (doBeginUpdateResult)
    {
        /**
         * Successful.
         */
    }
    else
    {    
        /**
         * Get the error from Api::BeginUpdate().
         */ 
        ErrorCode errorCode = WEAVERRUNTIME_EXPECT_ERROR(doBeginUpdateResult);

    }
}
```

您可以將 的傳回類型變更為 ，`Update()`將 的錯誤碼`BeginUpdate()`提供給呼叫 `Update()` 的函數`Aws::WeaverRuntime::Result<void>`。您可以重複此程序，讓錯誤碼繼續沿著呼叫堆疊傳送。