WebAssembly.Exception.prototype.getArg()

getArg()Exception 物件的原型方法,可用於獲取異常資料引數中指定項的值。

該方法傳遞一個 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,外部程式碼可以呼叫該方法以使用該標籤丟擲異常。

wasm
(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 模組,只是將匯入替換為匯出。

wasm
(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

瀏覽器相容性

BCD 表格僅在啟用了 JavaScript 的瀏覽器中載入。

另請參閱