My perspective differs from @superhawk610 on this matter
Throwing a JS error from WebAssembly is not something that can be easily done
While it is technically possible to throw an error, the practicality of it may be questionable. In most cases, implementing some Promise
logic as suggested by @superhawk610 would be more reasonable. However, if you are determined to throw an exception, here is a simple example.
example
1. Create a throw function stub
// Throw function stub for throwing javascript exceptions
// No implementation!
func Throw(exception string, message string)
2. Provide assembler hint with yourpkg_js.s file
// Implementation for throwing javascript exceptions
TEXT ·Throw(SB), NOSPLIT, $0
CallImport
RET
3. Extend wasm_exec / your wasm importObject with a js callback
this.importObject = {
go: {
// ...
// func Throw(exception string, message string)
'<your-pkg-import-path>.Throw': (sp) => {
const exception = loadString(sp + 8)
const message = loadString(sp + 24)
const throwable = globalThis[exception](message)
throw throwable
}
}
}
Now you can throw errors using the Error
class name and a custom message. For example:
func main () {
Throw("TypeError", "invalid arguments")
}