dop251 / goja

ECMAScript/JavaScript engine in pure Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Throwing an Exception within a ProxyTrapConfig Callback

Simerax opened this issue · comments

As I understand, the way of throwing exceptions from Go is by creating functions which return error as their second value.
This is not possible in a ProxyTrapConfig because these functions don't have the correct return type.

How could I throw an exception from within a ProxyTrapConfig Callback? (Or really an non matching function)

I tried creating an error with runtime.NewGoError but that does not work and is just handled like a regular Value.

package main

import (
	"errors"
	"fmt"

	"github.com/dop251/goja"
)

func main() {
	runtime := goja.New()

	proxy := runtime.NewProxy(runtime.NewObject(), &goja.ProxyTrapConfig{
		Get: func(target *goja.Object, property string, receiver goja.Value) goja.Value {
			return runtime.NewGoError(errors.New("oops"))
		},
	})

	runtime.Set("p", proxy)
	v, err := runtime.RunString("p.x")
	fmt.Println(v, err) // GoError: oops <nil>
}

You can panic with a goja.Value. See https://github.com/dop251/goja#exceptions

If a native Go function panics with a Value, it is thrown as a Javascript exception (and therefore can be caught):

var MyErr = errors.New("oops")

func main() {

	runtime := goja.New()

	proxy := runtime.NewProxy(runtime.NewObject(), &goja.ProxyTrapConfig{
		Get: func(target *goja.Object, property string, receiver goja.Value) goja.Value {
			panic(runtime.ToValue(MyErr))
		},
	})

	runtime.Set("p", proxy)
	v, err := runtime.RunString("p.x")
	fmt.Println(v, err) // <nil> oops at <eval>:1:1(1)
}

Thank you! should have read the documentation more closely...