WebAssembly.Exception.prototype.stack
非標準:此特性未標準化。我們不建議在生產環境中使用非標準特性,因為它們瀏覽器支援有限,並且可能會更改或被移除。但是,在沒有標準選項的特定情況下,它們可以是合適的替代方案。
WebAssembly.Exception 物件的只讀 stack 屬性可能包含堆疊跟蹤。
預設情況下,WebAssembly 程式碼丟擲的異常不包含堆疊跟蹤。
如果 WebAssembly 程式碼需要提供堆疊跟蹤,它必須呼叫 JavaScript 函式來建立異常,並在建構函式中傳遞 options.traceStack=true 引數。然後,虛擬機器可以將堆疊跟蹤附加到建構函式返回的異常物件上。
注意:為了提高效能,通常不會從 WebAssembly 程式碼傳送堆疊跟蹤。為這些異常新增堆疊跟蹤的功能是為開發工具提供的,通常不建議廣泛使用。
值
包含堆疊跟蹤的字串,如果未分配跟蹤,則為undefined。
堆疊跟蹤字串以 WebAssembly 格式列出了堆疊上每個操作的位置。這是一個人類可讀的字串,指示模組二進位制檔案中的 URL、呼叫的函式型別名稱、函式索引及其偏移量。它大致格式如下(有關更多資訊,請參閱規範中的堆疊跟蹤約定)
${url}:wasm-function[${funcIndex}]:${pcOffset}
示例
本示例演示瞭如何從包含堆疊跟蹤的 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 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。
瀏覽器相容性
載入中…