英文:
How to keep Golang WebAssembly Instance Running after error and Exit (Code:2)
问题
我有一个程序,用于将字节从JavaScript发送到Golang WebAssembly,使用以下代码:
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))
}
当我使用除Uint8Array
之外的其他内容执行sendBytes
时,整个实例都会在浏览器中被终止,我必须重新运行它。这是我执行sendBytes()的屏幕截图。
如何在发生任何错误时保持程序运行?
英文:
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 screenshot of how I execute sendBytes().
How can I keep it running no matter what error happened?
答案1
得分: 3
根据你的截图,当你将一个数字传递给sendBytes()
函数时,代码中的array.Length()
这一行会导致程序崩溃,然后WASM代码会退出。你知道sendBytes()
函数不应该被传递一个数字作为参数。
如果你确实需要让程序继续运行,你可以在Go语言中使用recover
函数,类似于以下代码:
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
}
// ...
}
这样,当sendBytes()
函数发生panic时,程序会通过recover()
函数进行恢复,并打印出panic的信息。
英文:
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
}
// ...
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论