Browse Source

Wrap error returned by MarshalJSON() in GoError. Added Exception.Unwrap() which unwraps GoError. Fixes #540.

Dmitry Panov 2 years ago
parent
commit
873a1496dc
3 changed files with 32 additions and 1 deletions
  1. 1 1
      builtin_json.go
  2. 19 0
      builtin_json_test.go
  3. 12 0
      runtime.go

+ 1 - 1
builtin_json.go

@@ -316,7 +316,7 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
 			} else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
 			} else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
 				b, err := v.MarshalJSON()
 				b, err := v.MarshalJSON()
 				if err != nil {
 				if err != nil {
-					panic(err)
+					panic(ctx.r.NewGoError(err))
 				}
 				}
 				ctx.buf.Write(b)
 				ctx.buf.Write(b)
 				ctx.allAscii = false
 				ctx.allAscii = false

+ 19 - 0
builtin_json_test.go

@@ -2,6 +2,7 @@ package goja
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
+	"errors"
 	"strings"
 	"strings"
 	"testing"
 	"testing"
 	"time"
 	"time"
@@ -78,6 +79,24 @@ func TestEOFWrapping(t *testing.T) {
 	}
 	}
 }
 }
 
 
+type testMarshalJSONErrorStruct struct {
+	e error
+}
+
+func (s *testMarshalJSONErrorStruct) MarshalJSON() ([]byte, error) {
+	return nil, s.e
+}
+
+func TestMarshalJSONError(t *testing.T) {
+	vm := New()
+	v := testMarshalJSONErrorStruct{e: errors.New("test error")}
+	vm.Set("v", &v)
+	_, err := vm.RunString("JSON.stringify(v)")
+	if !errors.Is(err, v.e) {
+		t.Fatalf("Unexpected error: %v", err)
+	}
+}
+
 func BenchmarkJSONStringify(b *testing.B) {
 func BenchmarkJSONStringify(b *testing.B) {
 	b.StopTimer()
 	b.StopTimer()
 	vm := New()
 	vm := New()

+ 12 - 0
runtime.go

@@ -399,6 +399,18 @@ func (e *Exception) Value() Value {
 	return e.val
 	return e.val
 }
 }
 
 
+func (e *Exception) Unwrap() error {
+	if obj, ok := e.val.(*Object); ok {
+		if obj.runtime.getGoError().self.hasInstance(obj) {
+			if val := obj.Get("value"); val != nil {
+				e1, _ := val.Export().(error)
+				return e1
+			}
+		}
+	}
+	return nil
+}
+
 func (r *Runtime) createIterProto(val *Object) objectImpl {
 func (r *Runtime) createIterProto(val *Object) objectImpl {
 	o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)
 	o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)