Skip to content

Commit

Permalink
toString() returns String() for wrapped fmt.Stringer and Error() for …
Browse files Browse the repository at this point in the history
…wrapped error (instead of "[object Object]").
  • Loading branch information
dop251 committed Jul 21, 2020
1 parent 1f8a2ff commit a695b0c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
5 changes: 4 additions & 1 deletion object_goreflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,10 +344,13 @@ func (o *objectGoReflect) _toString() Value {
return stringFalse
}
}
switch v := o.value.Interface().(type) {
switch v := o.origValue.Interface().(type) {
case fmt.Stringer:
return newStringValue(v.String())
case error:
return newStringValue(v.Error())
}

return stringObjectObject
}

Expand Down
13 changes: 13 additions & 0 deletions object_goreflect_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package goja

import (
"errors"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -989,6 +990,18 @@ func TestPrimitivePtr(t *testing.T) {
}
}

func TestStringer(t *testing.T) {
vm := New()
vm.Set("e", errors.New("test"))
res, err := vm.RunString("e.toString()")
if err != nil {
t.Fatal(err)
}
if v := res.Export(); v != "test" {
t.Fatalf("v: %v", v)
}
}

func ExampleTagFieldNameMapper() {
vm := New()
vm.SetFieldNameMapper(TagFieldNameMapper("json", true))
Expand Down

0 comments on commit a695b0c

Please sign in to comment.