WebAssembly.Exception.prototype.stack
非標準:此功能是非標準的,並且不在標準跟蹤中。請勿在面向 Web 的生產站點上使用它:它不會對每個使用者都起作用。實現之間也可能存在較大的不相容性,並且行為將來可能會發生變化。
型別為 WebAssembly.Exception 的物件例項的只讀stack屬性可能包含堆疊跟蹤。
來自 WebAssembly 程式碼的異常預設情況下不包含堆疊跟蹤。
如果 WebAssembly 程式碼需要提供堆疊跟蹤,則必須呼叫 JavaScript 函式來建立異常,並在 建構函式中傳遞options.traceStack=true引數。然後,虛擬機器可以將堆疊跟蹤附加到建構函式返回的異常物件。
注意:通常不會從 WebAssembly 程式碼傳送堆疊跟蹤以提高效能。新增堆疊跟蹤到這些異常的功能是為了開發人員工具,通常不建議廣泛使用。
值
示例
此示例演示如何從包含堆疊跟蹤的 WebAssembly 中丟擲異常。
考慮以下 WebAssembly 程式碼,假設它已編譯到名為example.wasm的檔案中。它匯入一個標籤,在內部將其稱為$tagname,並匯入一個它稱為$throwExnWithStack的函式。它匯出方法run,外部程式碼可以呼叫該方法來呼叫$throwExnWithStack(以及 JavaScript 函式)。
(module
;; import tag that will be referred to here as $tagname
(import "extmod" "exttag" (tag $tagname (param i32)))
;; import function that will be referred to here as $throwExnWithStack
(import "extmod" "throwExnWithStack" (func $throwExnWithStack (param i32)))
;; call $throwExnWithStack passing 42 as parameter
(func (export "run")
i32.const 42
call $throwExnWithStack
)
)
下面的 JavaScript 程式碼定義了一個新標籤tag和函式throwExceptionWithStack。在例項化 WebAssembly 模組時,這些將作為importObject傳遞給 WebAssembly 模組。
檔案例項化後,程式碼呼叫匯出的 WebAssembly run()方法,該方法將立即丟擲異常。然後從catch語句記錄堆疊。
const tag = new WebAssembly.Tag({ parameters: ["i32"] });
function throwExceptionWithStack(param) {
// Note: We declare the exception with "{traceStack: true}"
throw new WebAssembly.Exception(tag, [param], { traceStack: true });
}
// Note: importObject properties match the WebAssembly import statements.
const importObject = {
extmod: {
exttag: tag,
throwExnWithStack: throwExceptionWithStack,
},
};
WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
.then((obj) => {
console.log(obj.instance.exports.run());
})
.catch((e) => {
console.log(`stack: ${e.stack}`);
});
//Log output (something like):
// stack: throwExceptionWithStack@http://<url>/main.js:76:9
// @http://<url>/example.wasm:wasm-function[3]:0x73
// @http://<url>/main.js:82:38
此程式碼中最“相關”的部分是建立異常的行
new WebAssembly.Exception(tag, [param], { traceStack: true });
傳入{traceStack: true}告訴 WebAssembly 虛擬機器它應該將堆疊跟蹤附加到返回的WebAssembly.Exception。如果沒有此引數,堆疊將為undefined。
瀏覽器相容性
BCD 表僅在瀏覽器中載入