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

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 时, 我在浏览器中杀死了我的整个实例,我必须再次 运行 它。这是 screenshot of how I execute sendBytes().

无论发生什么错误,我如何保持它 运行ning?

根据您的屏幕截图,当您将数字传递给 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
    }
    // ...
}