如何在 Golang WebAssembly 实例出现错误和退出后保持运行状态(代码:2)

huangapple go评论90阅读模式
英文:

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) &lt; 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(&quot;sendBytes&quot;, 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().
如何在 Golang WebAssembly 实例出现错误和退出后保持运行状态(代码:2)

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(&quot;Recovered from&quot;, r)
        }
    }() 

    if len(args) &lt; 1 {
        return 0
    }
    // ...
}


</details>



huangapple
  • 本文由 发表于 2021年9月29日 22:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69378629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定