Skip to content

Commit

Permalink
Wrap error returned by MarshalJSON() in GoError. Added Exception.Unwr…
Browse files Browse the repository at this point in the history
…ap() which unwraps GoError. Fixes #540.
  • Loading branch information
dop251 committed Oct 14, 2023
1 parent acb9272 commit 873a149
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion builtin_json.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ func (ctx *_builtinJSON_stringifyContext) str(key Value, holder *Object) bool {
} else if v, ok := o1.origValue.Interface().(json.Marshaler); ok {
b, err := v.MarshalJSON()
if err != nil {
panic(err)
panic(ctx.r.NewGoError(err))
}
ctx.buf.Write(b)
ctx.allAscii = false
Expand Down
19 changes: 19 additions & 0 deletions builtin_json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package goja

import (
"encoding/json"
"errors"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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) {
b.StopTimer()
vm := New()
Expand Down
12 changes: 12 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,18 @@ func (e *Exception) Value() Value {
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 {
o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)

Expand Down

0 comments on commit 873a149

Please sign in to comment.