

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

# 適用於 Node.js Canary 的程式庫函數
<a name="Library_function_Nodejs"></a>

本節說明使用 Node.js 執行期的 Canary 指令碼可用的程式庫函數。

**Topics**
+ [addExecutionError(errorMessage, ex)；](#Library_function_Nodejs_addExecutionError_Nodecanary)
+ [getCanaryName();](#Library_function_Nodejs_getCanaryName)
+ [getCanaryArn();](#Library_function_Nodejs_Nodecanary)
+ [getCanaryUserAgentString();](#Library_function_Nodejs_getCanaryUserAgentString_Nodecanary)
+ [getRuntimeVersion();](#Library_function_Nodejs_getRuntimeVersion_Nodecanary)
+ [getLogLevel();](#Library_function_Nodejs_getLogLevel_Nodecanary)
+ [setLogLevel();](#Library_function_Nodejs_setLogLevel_Nodecanary)
+ [executeStep(stepName， functionToExecute， 【stepConfig】)](#Library_function_Nodejs_executestep_Nodecanary)
+ [executeHttpStep(stepName, requestOptions, [callback], [stepConfig])](#Library_function_Nodejs_executeHttpStep)

## addExecutionError(errorMessage, ex)；
<a name="Library_function_Nodejs_addExecutionError_Nodecanary"></a>

`errorMessage` 描述錯誤，而 `ex` 是遇到的例外狀況

您可以使用 `addExecutionError` 為您的 Canary 設定執行錯誤。它會在不中斷指令碼執行的情況下使 Canary 失敗。它也不會影響您的 `successPercent` 指標。

只有在錯誤表示 Canary 指令碼成功或失敗並不重要時，才應將錯誤追蹤為執行錯誤。

`addExecutionError` 的使用範例如下所示。您正在監控端點的可用性，並在頁面載入後擷取螢幕擷取畫面。由於擷取螢幕擷取畫面的失敗並不會決定端點的可用性，因此您可以捕捉擷取螢幕擷取畫面時遇到的任何錯誤，並將它們新增為執行錯誤。您的可用性指標仍會顯示端點已啟動並執行，但您的 Canary 狀態會標示為失敗。下面的範本程式碼區塊可捕獲這樣的錯誤，並將其新增為執行錯誤。

```
try {await synthetics.executeStep(stepName, callbackFunc);} catch(ex) {synthetics.addExecutionError('Unable to take screenshot ', ex);}
```

## getCanaryName();
<a name="Library_function_Nodejs_getCanaryName"></a>

傳回 Canary 的名稱。

## getCanaryArn();
<a name="Library_function_Nodejs_Nodecanary"></a>

傳回 Canary 的 ARN。

## getCanaryUserAgentString();
<a name="Library_function_Nodejs_getCanaryUserAgentString_Nodecanary"></a>

傳回 Canary 的自訂使用者代理程式。

## getRuntimeVersion();
<a name="Library_function_Nodejs_getRuntimeVersion_Nodecanary"></a>

此函數適用於執行時間版本 `syn-nodejs-3.0`和更新版本。其會傳回 Canary 的 Synthetics 執行時間版本。例如，傳回值可以是 `syn-nodejs-3.0`。

## getLogLevel();
<a name="Library_function_Nodejs_getLogLevel_Nodecanary"></a>

擷取 Synthetics 程式庫的目前日誌層級。可能的值如下：
+ `0` – 偵錯
+ `1` – 資訊
+ `2` – 警告
+ `3` – 錯誤

範例：

```
let logLevel = synthetics.getLogLevel();
```

## setLogLevel();
<a name="Library_function_Nodejs_setLogLevel_Nodecanary"></a>

設定 Synthetics 程式庫的日誌層級。可能的值如下：
+ `0` – 偵錯
+ `1` – 資訊
+ `2` – 警告
+ `3` – 錯誤

範例：

```
synthetics.setLogLevel(0);
```

## executeStep(stepName， functionToExecute， 【stepConfig】)
<a name="Library_function_Nodejs_executestep_Nodecanary"></a>

執行提供的步驟，將其包裝為start/pass/fail記錄，以及通過/失敗和持續時間指標。

`executeStep` 函數還會執行下列操作：
+ 步驟開始的日誌
+ 啟動計時器
+ 執行提供的函數
+ 當函數正常傳回時，它會計為傳遞。如果函數擲回，則會計為失敗
+ 結束計時器
+ 記錄步驟是否已通過或失敗
+ 發出`stepName SuccessPercent`指標，傳遞為 100，失敗為 0
+ 發出 `stepName Duration metric`，其值是根據步驟開始和結束時間
+ 傳回 functionToExecute ` functionToExecute` 傳回的內容或擲回的內容
+ 將步驟執行摘要新增至 Canary 的報告

 **範例** 

```
await synthetics.executeStep(stepName, async function () {
    return new Promise((resolve, reject) => {
        const req = https.request(url, (res) => {
            console.log(`Status: ${res.statusCode}`);
            if (res.statusCode >= 400) {
                reject(new Error(`Request failed with status ${res.statusCode} for ${url}`));
            } else {
                resolve();
            }
        });

        req.on('error', (err) => {
            reject(new Error(`Request failed for ${url}: ${err.message}`));
        });

        req.end();
    });
});
```

## executeHttpStep(stepName, requestOptions, [callback], [stepConfig])
<a name="Library_function_Nodejs_executeHttpStep"></a>

執行提供的 HTTP 請求作為一個步驟，並發布 `SuccessPercent` (通過/失敗) 和 `Duration` 指標。

**executeHttpStep** 根據請求中指定的通訊協定，深入使用 HTTP 或 HTTPS 原生函數。

此函數也會將步驟執行摘要新增至 Canary 報告。摘要包含每個 HTTP 請求的詳細資訊，如下所示：
+ 開始時間
+ 結束時間
+ 狀態 (通過/失敗)
+ 失敗的原因，如果失敗
+ HTTP 呼叫詳細資訊，如請求/回應標頭、內文、狀態碼、狀態訊息和效能計時。

**Topics**
+ [Parameters](#Library_function_Nodejs_executeHttpStep_parameters_Nodecanary)
+ [使用 executeHttpStep 的範例](#Library_function_Nodejs_executeHttpStep_examples_Nodecanary)

### Parameters
<a name="Library_function_Nodejs_executeHttpStep_parameters_Nodecanary"></a>

 **stepName({{String}})** 

指定步驟的名稱。此名稱也可用於發布此步驟的 CloudWatch 指標。

 **requestOptions({{Object or String}})** 

此參數的值可以是 URL、URL 字串或物件。如果它是一個物件，那麼它必須是可設定的選項組，以發出 HTTP 請求。它支援 Node.js 文件中的 [ http.request(options[, callback])](https://nodejs.org/api/http.html#http_http_request_options_callback) 的所有選項。

除了這些 Node.js 選項之外，**requestOptions** 支援其他參數 `body`。您可以使用 `body` 參數將資料作為請求內文進行傳遞。

 **callback({{response}})** 

(選用) 這是使用 HTTP 回應呼叫的使用者函數。回應的類型為 [Class: http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)。

 **stepConfig({{object}})** 

(選用) 使用此參數，以此步驟的不同組態覆寫全域綜合組態。

### 使用 executeHttpStep 的範例
<a name="Library_function_Nodejs_executeHttpStep_examples_Nodecanary"></a>

以下範例系列會建立會相互建置，以說明此選項的各種用途。

這第一個範例設定了請求參數。您可以傳遞 URL 做為 ** requestOptions**：

```
let requestOptions = 'https://www.amazon.com';
```

或者你可以傳遞選項集：

```
let requestOptions = {
        'hostname': 'myproductsEndpoint.com',
        'method': 'GET',
        'path': '/test/product/validProductName',
        'port': 443,
        'protocol': 'https:'
    };
```

下一個範例會建立接受回應的回呼函數。預設情況下，如果未指定**回呼**，CloudWatch Synthetics 會驗證狀態是否介於 200 到 299 之間。

```
// Handle validation for positive scenario
    const callback = async function(res) {
        return new Promise((resolve, reject) => {
            if (res.statusCode < 200 || res.statusCode > 299) {
                throw res.statusCode + ' ' + res.statusMessage;
            }
     
            let responseBody = '';
            res.on('data', (d) => {
                responseBody += d;
            });
     
            res.on('end', () => {
                // Add validation on 'responseBody' here if required. For ex, your status code is 200 but data might be empty
                resolve();
            });
        });
    };
```

下一個範例會為此步驟建立覆寫全域 CloudWatch Synthetics 組態的組態。此範例中的步驟組態允許在您的報告中包含請求標頭、回應標頭、請求內文 (發佈資料) 和回應內文，並限制 'X-Amz-Security-Token' 和 'Authorization' 標頭值。根據預設，基於安全性考量，這些值不會包含在報告中。如果選擇包含它們，則資料只會存放於 S3 儲存貯體中。

```
// By default headers, post data, and response body are not included in the report for security reasons. 
// Change the configuration at global level or add as step configuration for individual steps
let stepConfig = {
    includeRequestHeaders: true, 
    includeResponseHeaders: true,
    restrictedHeaders: ['X-Amz-Security-Token', 'Authorization'], // Restricted header values do not appear in report generated.
    includeRequestBody: true,
    includeResponseBody: true
};
```

這最後一個範例會將您的請求傳遞給 **executeHttpStep**，並命名步驟。

```
await synthetics.executeHttpStep('Verify GET products API', requestOptions, callback, stepConfig);
```

透過這組範例，CloudWatch Synthetics 會新增報告中每個步驟的詳細資料，並使用 **stepName**。

 您將看見適用於 `Verify GET products API` 步驟的 `successPercent` 和`duration`的 指標步驟。您可以監控 API 呼叫步驟的指標，以監控您的 API 效能。

如需使用這些函數的完整指令碼範例，請參閱 [多步驟 API Canary](CloudWatch_Synthetics_Canaries_Samples.md#CloudWatch_Synthetics_Canaries_Samples_APIsteps)。