共用方式為


使用 Dev Proxy 除錯

一目了然
目標:在 Dev Proxy 模擬 API 錯誤時,偵錯您的應用程式
時間: 15分鐘
插件:GenericRandomErrorPlugin
前置條件:設定開發代理,VS Code

當你建立能呼叫 API 的應用程式時,你需要確保程式碼能妥善處理錯誤。 結合 Dev Proxy 與 Visual Studio(VS) Code 的除錯器,你可以模擬 API 錯誤,並逐步檢視錯誤處理程式碼以驗證其正確運作。

概觀

使用 Dev Proxy 除錯包含三個步驟:

  1. 設定 VS Code 讓 HTTP 請求透過開發代理路由
  2. 設定開發代理伺服器來模擬特定錯誤
  3. 在錯誤處理程式碼中設定斷點並除錯

將 VS Code 設定為使用 Dev Proxy 進行除錯

你怎麼設定 VS Code 取決於你使用的程式語言。 以下章節將展示如何為 Node.js、.NET及Python應用程式配置 VS Code。

Node.js

若要用開發代理除錯 Node.js 應用程式,請設定 檔案設定代理環境變數並停用 TLS/SSL 憑證驗證。

檔案: .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug with Dev Proxy",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}/index.js",
      "env": {
        "NODE_ENV": "development",
        "http_proxy": "http://127.0.0.1:8000",
        "https_proxy": "http://127.0.0.1:8000",
        "GLOBAL_AGENT_HTTP_PROXY": "http://127.0.0.1:8000",
        "NODE_TLS_REJECT_UNAUTHORIZED": "0"
      }
    }
  ]
}

這很重要

設定會 停用 TLS/SSL 憑證驗證。 只在開發時使用這個設定。 為了更安全的方式,請直接信任 開發代理憑證:

macOS/Linux:

"NODE_EXTRA_CA_CERTS": "${env:HOME}/.devproxy/rootCert.pem"

Windows:

"NODE_EXTRA_CA_CERTS": "${env:USERPROFILE}\\.devproxy\\rootCert.pem"

這個變數被套件使用,套件為許多 Node.js HTTP 函式庫提供代理支援。 欲了解更多關於配置不同 HTTP 函式庫的資訊,請參見「 在 Node.js 應用程式中使用開發代理」。

.NET

.NET 應用程式會自動使用系統代理設定。 要用開發代理除錯 .NET 應用程式,通常不需要設定任何環境變數。 建立基本的除錯設定:

檔案: .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug with Dev Proxy",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      "program": "${workspaceFolder}/bin/Debug/net8.0/MyApp.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "console": "internalConsole",
      "stopAtEntry": false
    }
  ]
}

如果你的應用程式沒有偵測系統代理,請明確設定代理環境變數:

檔案: .vscode/launch.json(包含明確代理設定)

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug with Dev Proxy",
      "type": "coreclr",
      "request": "launch",
      "preLaunchTask": "build",
      "program": "${workspaceFolder}/bin/Debug/net8.0/MyApp.dll",
      "args": [],
      "cwd": "${workspaceFolder}",
      "console": "internalConsole",
      "stopAtEntry": false,
      "env": {
        "http_proxy": "http://127.0.0.1:8000",
        "https_proxy": "http://127.0.0.1:8000"
      }
    }
  ]
}

小提示

在 Windows 和 macOS 上,如果你在 Dev 代理設定 時安裝了 Dev Proxy 憑證,.NET 會自動信任它。 在 Linux 上,你可能需要手動信任憑證。 請參閱你發行版關於配置受信任憑證的文件。

Python

要用 Dev Proxy 除錯 Python 應用程式,請設定 launch.json 檔案來設定代理環境變數。 設定取決於你 使用函式庫還是其他 HTTP 函式庫。

檔案: .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug with Dev Proxy",
      "type": "debugpy",
      "request": "launch",
      "program": "${workspaceFolder}/main.py",
      "console": "integratedTerminal",
      "env": {
        "HTTP_PROXY": "http://127.0.0.1:8000",
        "HTTPS_PROXY": "http://127.0.0.1:8000",
        "REQUESTS_CA_BUNDLE": ""
      }
    }
  ]
}

這很重要

設定 為空字串會 讓函式庫跳過 TLS/SSL 憑證驗證。 只在開發時使用這個設定。

若想更安全,可以參考 Dev Proxy 憑證:

macOS/Linux:

"REQUESTS_CA_BUNDLE": "${env:HOME}/.devproxy/rootCert.pem"

Windows:

"REQUESTS_CA_BUNDLE": "${env:USERPROFILE}\\.devproxy\\rootCert.pem"

如果你使用函式庫, 請改用 環境變數設定 TLS/SSL 驗證:

{
  "env": {
    "HTTP_PROXY": "http://127.0.0.1:8000",
    "HTTPS_PROXY": "http://127.0.0.1:8000",
    "TLS/SSL_CERT_FILE": "${env:HOME}/.devproxy/rootCert.pem"
  }
}

設定開發代理以模擬錯誤

要除錯錯誤處理,請設定 Dev Proxy,使其在您的應用程式呼叫 API 時回傳特定的錯誤。 使用 GenericRandomErrorPlugin 來模擬像 <錯誤1> 或 <錯誤2> 的錯誤。

模擬 429(請求過多)錯誤

建立一個模擬流量限制的開發代理設定檔:

檔案: devproxyrc.json

{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.3.0/rc.schema.json",
  "plugins": [
    {
      "name": "GenericRandomErrorPlugin",
      "enabled": true,
      "pluginPath": "~appFolder/plugins/DevProxy.Plugins.dll",
      "configSection": "errorsConfig"
    }
  ],
  "urlsToWatch": [
    "https://api.contoso.com/*"
  ],
  "rate": 100,
  "errorsConfig": {
    "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.3.0/genericrandomerrorplugin.schema.json",
    "errorsFile": "errors.json"
  }
}

建立包含特定錯誤回應的錯誤檔案:

檔案: errors.json

{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.3.0/genericrandomerrorplugin.errorsfile.schema.json",
  "errors": [
    {
      "request": {
        "url": "https://api.contoso.com/*"
      },
      "responses": [
        {
          "statusCode": 429,
          "headers": [
            {
              "name": "content-type",
              "value": "application/json"
            },
            {
              "name": "Retry-After",
              "value": "60"
            }
          ],
          "body": {
            "error": {
              "code": "TooManyRequests",
              "message": "Rate limit exceeded. Retry after 60 seconds."
            }
          }
        }
      ]
    }
  ]
}

小提示

設定 為 讓每個請求都失敗,這樣你在除錯時就能穩定命中錯誤處理程式碼。 想測試間歇性錯誤時,降低速率。

模擬 500(內部伺服器錯誤)

為了模擬伺服器錯誤,請新增另一個錯誤回應:

檔案: errors.json(多重錯誤)

{
  "$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v2.3.0/genericrandomerrorplugin.errorsfile.schema.json",
  "errors": [
    {
      "request": {
        "url": "https://api.contoso.com/*"
      },
      "responses": [
        {
          "statusCode": 429,
          "headers": [
            {
              "name": "content-type",
              "value": "application/json"
            },
            {
              "name": "Retry-After",
              "value": "60"
            }
          ],
          "body": {
            "error": {
              "code": "TooManyRequests",
              "message": "Rate limit exceeded. Retry after 60 seconds."
            }
          }
        },
        {
          "statusCode": 500,
          "headers": [
            {
              "name": "content-type",
              "value": "application/json"
            }
          ],
          "body": {
            "error": {
              "code": "InternalServerError",
              "message": "An unexpected error occurred."
            }
          }
        }
      ]
    }
  ]
}

當你定義多個錯誤回應時,Dev Proxy 會隨機為每個攔截的請求選出一個。

除錯你的錯誤處理程式碼

設定好 VS Code 和 Dev Proxy 後,你現在可以除錯錯誤處理程式碼。

步驟 1:設定斷點

打開原始碼,並在錯誤處理程式碼中設定斷點。 例如,在 Node.js 應用中:

async function fetchData() {
  try {
    const response = await fetch('https://api.contoso.com/data');
    
    if (!response.ok) {
      // Set a breakpoint here to debug error responses
      throw new Error(`HTTP error: ${response.status}`);
    }
    
    return await response.json();
  } catch (error) {
    // Set a breakpoint here to debug exceptions
    console.error('Failed to fetch data:', error);
    throw error;
  }
}

步驟 2:啟動開發代理

用你的設定檔啟動開發代理:

devproxy --config-file devproxyrc.json

步驟 3:開始在 VS Code 中除錯

  1. 開啟 VS Code
  2. 按 F5 或選擇 執行 開始除錯
  3. 當你的應用程式呼叫 API 時,Dev Proxy 會攔截並回傳錯誤
  4. VS Code 會在你的斷點處暫停
  5. 使用除錯控制項逐步檢視程式碼並檢查變數

步驟四:檢查錯誤

當 VS Code 在你的斷點暫停時,請使用偵錯面板來:

  • 查看錯誤回應狀態碼與訊息
  • 檢查當地變數的值
  • 請逐步檢查您的重試邏輯
  • 確認你的錯誤訊息是否易於使用

自動啟動與停止開發代理伺服器

為了簡化你的除錯工作流程,設定 VS Code 在你開始除錯時自動啟動 Dev Proxy,完成後停止。 安裝 Dev Proxy Toolkit 擴充功能 並設定任務:

檔案: .vscode/tasks.json

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "devproxy-start",
      "type": "devproxy",
      "command": "start",
      "args": [
        "--config-file",
        "devproxyrc.json"
      ],
      "isBackground": true,
      "problemMatcher": "$devproxy-watch"
    },
    {
      "label": "devproxy-stop",
      "type": "devproxy",
      "command": "stop"
    }
  ]
}

要使用這些任務,請更新你的 :

檔案: .vscode/launch.json(Node.js 自動啟動)

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug with Dev Proxy",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}/index.js",
      "preLaunchTask": "devproxy-start",
      "postDebugTask": "devproxy-stop",
      "env": {
        "NODE_ENV": "development",
        "http_proxy": "http://127.0.0.1:8000",
        "https_proxy": "http://127.0.0.1:8000",
        "GLOBAL_AGENT_HTTP_PROXY": "http://127.0.0.1:8000",
        "NODE_TLS_REJECT_UNAUTHORIZED": "0"
      }
    }
  ]
}

有效除錯的技巧

  • 為了讓每次請求都失敗,請在開發代理設定中配置,以便穩定擊中斷點。
  • 要了解程式碼如何處理特定錯誤,除錯時使用單一錯誤回應。
  • 要確認你的程式碼是否符合流量限制,請檢查它在偵錯 429 錯誤碼時是否讀取並遵循 HTTP 標頭。
  • 為了確保程式碼能優雅地處理異常回應,請使用 Dev Proxy 模擬像是 JSON 格式錯誤或標頭缺失等邊緣情況。
  • 要只在特定錯誤上斷開,可以在 VS Code 中使用條件斷點,方法是右鍵點擊斷點,並加上一個條件,例如if (x > 5)。

另請參閱