WebAssembly.Exception.prototype.getArg()
getArg()
实例方法可用于获取异常数据参数中指定项的值。
该方法会传递一个 WebAssembly.Tag
,并且只有当抛出的 Exception
是使用相同的标签创建的,该方法才会成功,否则会抛出 TypeError
。这确保了只有当调用代码能够访问标签时,才能读取异常。未导入或未从 WebAssembly 代码导出的标签是内部的,并且不能使用此方法查询其关联的 WebAssembly.Exception
!
注意: 仅标签具有相同的数据类型序列是不够的 — 它必须与创建异常时使用的标签具有相同的身份(即同一个标签)。
语法
getArg(exceptionTag, index)
参数
exceptionTag
-
一个必须与此异常关联的标签匹配的
WebAssembly.Tag
。 index
-
要返回的数据参数中的值的索引,从 0 开始计数。
返回值
index
处的参数值。
异常
TypeError
-
标签不匹配;异常不是使用传递给方法的标签创建的。
RangeError
-
index
参数的值大于或等于数据中的字段数。
示例
为了获取异常的值,调用代码必须“知道”该标签;它可以是从调用代码导入或导出的。
从导入的标签获取异常值
考虑以下 WebAssembly 代码,假定它被编译到一个名为“example.wasm”的文件中。此代码导入一个标签,该标签在内部称为 $tagname
,并导出一个 run
方法,外部代码可以调用该方法来使用该标签抛出一个异常。
(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()
方法,该方法将立即抛出一个异常。
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 模块,只是将导入替换为了导出。
(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()
方法测试是否是正确的标签。
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 |
浏览器兼容性
加载中…