How to catch exception when calling a "syscall/js" function?

Hello mate,
I’m experiencing the use of the syscall/js package and I need help to find a way to catch exception on a call to a js function.

Here an example:

value := js.Global().Get("window").Get("localStorage")
...

If you disable the access to the localstorage into your browser then it raise the following exception:

image

with no way to resume your wasm code.
Thank you for any help

The documentation of syscall/js says that js.Value.Get panics when a value is not a JavaScript object, so you should be able to “catch the exception” just like you would recover from a panic in other Go code:

func tryGet(v js.Value, p string) (result js.Value, err error) {
    defer func() {
        if x := recover(); x != nil {
            var ok bool
            if err, ok = x.(error); !ok {
                err = fmt.Errorf("%v", x)
            }
        }
    }()
    return v.Get(p), nil
}

Thank you @skillian
Unfortunately it does not work. The JS call exception does not make the go code panicking, so not recovery possible.
The go wasm code only… stops… at the .Get("localtorage") line

It looks like you might have to catch it on the JavaScript side and pass it back to Go.

I’m not familiar with JavaScript, so I don’t know if this is idiomatic or not, but I wrote:

function tryGet() {
	try {
		var source = arguments[0];

		for (var i = 1; i < arguments.length; i++)
			source = source[arguments[i]];

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

And then in my Go code:

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

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

On my computer, accessing window.localStorage did not throw an exception, but I got an error as the 2nd return value from tryGet if I used an invalid attribute name.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.