WebAssembly.Exception.prototype.getArg()

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上使用。自 2022 年 5 月以來,它已在各個瀏覽器中可用。

getArg() 例項方法可用於獲取異常資料引數中指定項的值。

該方法會傳遞一個 WebAssembly.Tag,並且只有當丟擲的 Exception 是使用相同的標籤建立的,該方法才會成功,否則會丟擲 TypeError。這確保了只有當呼叫程式碼能夠訪問標籤時,才能讀取異常。未匯入或未從 WebAssembly 程式碼匯出的標籤是內部的,並且不能使用此方法查詢其關聯的 WebAssembly.Exception

注意: 僅標籤具有相同的資料型別序列是不夠的 — 它必須與建立異常時使用的標籤具有相同的身份(即同一個標籤)。

語法

js
getArg(exceptionTag, index)

引數

exceptionTag

一個必須與此異常關聯的標籤匹配的 WebAssembly.Tag

index

要返回的資料引數中的值的索引,從 0 開始計數。

返回值

index 處的引數值。

異常

TypeError

標籤不匹配;異常不是使用傳遞給方法的標籤建立的。

RangeError

index 引數的值大於或等於資料中的欄位數。

示例

為了獲取異常的值,呼叫程式碼必須“知道”該標籤;它可以是從呼叫程式碼匯入或匯出的。

從匯入的標籤獲取異常值

考慮以下 WebAssembly 程式碼,假定它被編譯到一個名為“example.wasm”的檔案中。此程式碼匯入一個標籤,該標籤在內部稱為 $tagname,並匯出一個 run 方法,外部程式碼可以呼叫該方法來使用該標籤丟擲一個異常。

wat
(module
  ;; import tag that will be referred to here as $tagname
  (import "extmod" "exttag" (tag $tagname (param i32)))

  ;; $throwException function throws i32 param as a $tagname exception
  (func $throwException (param i32)
    local.get 0
    throw $tagname
  )

  ;; Exported function "run" that calls $throwException
  (func (export "run")
    i32.const 1
    call $throwException
  )
)

下面的程式碼呼叫 WebAssembly.instantiateStreaming 來匯入“example.wasm”檔案,並傳入一個“匯入物件”(importObject),該物件包含一個名為 tagToImport 的新的 WebAssembly.Tag。匯入物件定義了一個具有屬性的物件,這些屬性與 WebAssembly 程式碼中的 import 語句匹配。

檔案例項化後,程式碼將呼叫匯出的 WebAssembly run() 方法,該方法將立即丟擲一個異常。

js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32"] });

// Note: the import object properties match the import statement in WebAssembly code!
const importObject = {
  extmod: {
    exttag: tagToImport,
  },
};

WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
  .then((obj) => {
    console.log(obj.instance.exports.run());
  })
  .catch((e) => {
    console.error(e);
    console.log(`getArg 0 : ${e.getArg(tagToImport, 0)}`);
  });

/* Log output
example.js:40 WebAssembly.Exception: wasm exception
example.js:41 getArg 0 : 1
*/

程式碼捕獲該異常,並使用 getArg() 列印第一個索引處的值。在這種情況下,它只是“1”。

從匯出的標籤獲取異常值

使用匯出的標籤的過程與上一節所示非常相似。這是同一個 WebAssembly 模組,只是將匯入替換為了匯出。

wat
(module
  ;; Export tag giving it external name: "exptag"
  (tag $tagname (export "exptag") (param i32))

  (func $throwException (param i32)
    local.get 0
    throw $tagname
  )

  (func (export "run")
    i32.const 1
    call $throwException
  )
)

JavaScript 也類似。在這種情況下,我們沒有匯入,而是獲取匯出的標籤並使用它來獲取引數。為了使其更“安全”,我們在這裡還使用 is() 方法測試是否是正確的標籤。

js
let tagExportedFromWasm;

WebAssembly.instantiateStreaming(fetch("example.wasm"))
  .then((obj) => {
    // Import the tag using its name from the WebAssembly module
    tagExportedFromWasm = obj.instance.exports.exptag;
    console.log(obj.instance.exports.run());
  })
  .catch((e) => {
    console.error(e);
    // If the tag is correct, get the value
    if (e.is(tagExportedFromWasm)) {
      console.log(`getArg 0 : ${e.getArg(tagExportedFromWasm, 0)}`);
    }
  });

規範

規範
WebAssembly JavaScript 介面:異常處理
# dom-exception-getarg

瀏覽器相容性

另見