I have this program to send bytes from JavaScript to Golang WebAssembly using the code:
func sendBytes(this js.Value, args []js.Value) interface{} {
if len(args) < 1 {
return 0
}
array := args[0]
fmt.Println(array.Type())
buf := make([]byte, array.Length())
n := js.CopyBytesToGo(buf, array)
fmt.Println(buf)
return n
}
func registerCallbacks() {
js.Global().Set("sendBytes", js.FuncOf(sendBytes))
}
When I execute sendBytes
with something else than Uint8Array
,
I am getting my whole instance killed in the browser and I have to run it again. This is
How can I keep it running no matter what error happened?
CodePudding user response:
According to your screenshot, when you passed a number to sendBytes()
, the line of code array.Length()
would lead to a panic, then the WASM code would exit. As you know sendBytes()
should not be called on a number.
If you indeed need it to keep running, you can use recover
in Go, similar to:
func sendBytes(this js.Value, args []js.Value) interface{} {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from", r)
}
}()
if len(args) < 1 {
return 0
}
// ...
}