Tuesday, April 23, 2024
HomeGolangThe best way to catch exception when calling a "syscall/js" perform? -...

The best way to catch exception when calling a “syscall/js” perform? – Getting Assist


Hi there mate,
I’m experiencing the usage of the syscall/js bundle and I need assistance to discover a strategy to catch exception on a name to a js perform.

Right here an instance:

worth := js.World().Get("window").Get("localStorage")
...

If you happen to disable the entry to the localstorage into your browser then it increase the next exception:

with no strategy to resume your wasm code.
Thanks for any assist

The documentation of syscall/js says that js.Worth.Get panics when a price just isn’t a JavaScript object, so it’s best to be capable to “catch the exception” similar to you’ll get well from a panic in different Go code:

func tryGet(v js.Worth, p string) (outcome js.Worth, err error) {
    defer func() {
        if x := get well(); x != nil {
            var okay bool
            if err, okay = x.(error); !okay {
                err = fmt.Errorf("%v", x)
            }
        }
    }()
    return v.Get(p), nil
}

Thanks @skillian
Sadly it doesn’t work. The JS name exception doesn’t make the go code panicking, so not restoration attainable.
The go wasm code solely… stops… on the .Get("localtorage") line

It seems to be such as you may need to catch it on the JavaScript facet and move it again to Go.

I’m not conversant in JavaScript, so I don’t know if that is idiomatic or not, however I wrote:

perform tryGet() {
	attempt {
		var supply = arguments[0];

		for (var i = 1; i < arguments.size; i++)
			supply = supply[arguments[i]];

		return [source, null];
	}
	catch (err) {
		return [null, err];
	}
}

After which in my Go code:

func tryGet(supply js.Worth, path ...string) (js.Worth, error) {
	tryGetArgs := make([]any, len(path)+1)
	tryGetArgs[0] = supply
	for i, v := vary path {
		tryGetArgs[i+1] = js.ValueOf(v)
	}
	arr := js.World().Name("tryGet", tryGetArgs...)
	if arr1 := arr.Index(1); !arr1.Equal(js.Null()) {
		return js.Worth{}, &js.Error{arr1}
	}
	return arr.Index(0), nil
}

func principal() {
	keepMainRunning := make(chan struct{})
	v, err := tryGet(js.World(), "window", "localStorage")
	if err != nil {
		alert(err.Error())
		return
	}
	fmt.Println("results of tryGet:", v)
	<-keepMainRunning
}

On my pc, accessing window.localStorage didn’t throw an exception, however I bought an error because the 2nd return worth from tryGet if I used an invalid attribute identify.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments