The WebAssembly.Exception() constructor is used to create a new WebAssembly.Exception object instance.
new Exception(tag, payload)
new Exception(tag, payload, options)tagA WebAssembly.Tag instance defining the data types expected for each of the values in the payload.
payloadAn array of one or more data fields comprising the payload of the exception. The elements must match the data types of the corresponding elements in the tag. If the number of data fields in the payload and their types don't match, a TypeError exception is thrown.
options Optional An object with the following optional fields:
traceStack Optional true if the Exception may have a stack trace attached to its stack property, otherwise false. Defaults to false.
TypeErrorThe payload and tag sequences do not have the same number of elements and/or the elements are not of matching types.
The Exception() constructor accepts a WebAssembly.Tag, an array of values, and an options object as arguments. The tag uniquely defines the type of an exception, including the order of its arguments and their data types. The same tag that was used to create the Exception is required to access the arguments of a thrown exception (using Exception.prototype.getArg()).
You would not normally use this constructor to manually create a Wasm exception. Instead, a WebAssembly.Exception object is normally created when handling Wasm exceptions, for example:
WebAssembly.instantiateStreaming(fetch("module.wasm"), { env }).then(
(result) => {
try {
// Cause function to throw
result.instance.exports.throw(-1);
} catch (e) {
if (e instanceof WebAssembly.Exception && e.is(myErrorTag)) {
const errorCode = e.getArg(myErrorTag, 0); // 0 = first payload value
console.log("Error code:", errorCode); // 42
} else {
throw e; // throw other errors
}
}
},
);For a working example, see the throw instruction reference page.
This example shows manual creation of a WebAssembly.Exception instance.
// Create tag and use it to create an exception
const tag = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
const exception = new WebAssembly.Exception(tag, [42, 42.3]);Note: The stack example shows the creation of an exception that uses the options parameter.