Skip to content
This repository was archived by the owner on Dec 1, 2021. It is now read-only.

Commit 856c240

Browse files
flimzydavecheney
authored andcommitted
Add json.Marshaler support to the Frame type. (#197)
* Add json.Marshaler support to the Frame type. * Update regex for Go tip * Escape periods in regular expression tests * Implement encoding.TextMarshaler instead of json.Marshaler
1 parent ffb6e22 commit 856c240

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

json_test.go

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package errors
2+
3+
import (
4+
"encoding/json"
5+
"regexp"
6+
"testing"
7+
)
8+
9+
func TestFrameMarshalText(t *testing.T) {
10+
var tests = []struct {
11+
Frame
12+
want string
13+
}{{
14+
initpc,
15+
`^github.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+$`,
16+
}, {
17+
0,
18+
`^unknown$`,
19+
}}
20+
for i, tt := range tests {
21+
got, err := tt.Frame.MarshalText()
22+
if err != nil {
23+
t.Fatal(err)
24+
}
25+
if !regexp.MustCompile(tt.want).Match(got) {
26+
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
27+
}
28+
}
29+
}
30+
31+
func TestFrameMarshalJSON(t *testing.T) {
32+
var tests = []struct {
33+
Frame
34+
want string
35+
}{{
36+
initpc,
37+
`^"github\.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+"$`,
38+
}, {
39+
0,
40+
`^"unknown"$`,
41+
}}
42+
for i, tt := range tests {
43+
got, err := json.Marshal(tt.Frame)
44+
if err != nil {
45+
t.Fatal(err)
46+
}
47+
if !regexp.MustCompile(tt.want).Match(got) {
48+
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
49+
}
50+
}
51+
}

stack.go

+10
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,16 @@ func (f Frame) Format(s fmt.State, verb rune) {
8383
}
8484
}
8585

86+
// MarshalText formats a stacktrace Frame as a text string. The output is the
87+
// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
88+
func (f Frame) MarshalText() ([]byte, error) {
89+
name := f.name()
90+
if name == "unknown" {
91+
return []byte(name), nil
92+
}
93+
return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
94+
}
95+
8696
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
8797
type StackTrace []Frame
8898

0 commit comments

Comments
 (0)