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

Commit

Permalink
Add json.Marshaler support to the Frame type. (#197)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
flimzy authored and davecheney committed Feb 17, 2019
1 parent ffb6e22 commit 856c240
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
51 changes: 51 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package errors

import (
"encoding/json"
"regexp"
"testing"
)

func TestFrameMarshalText(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
initpc,
`^github.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+$`,
}, {
0,
`^unknown$`,
}}
for i, tt := range tests {
got, err := tt.Frame.MarshalText()
if err != nil {
t.Fatal(err)
}
if !regexp.MustCompile(tt.want).Match(got) {
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
}
}
}

func TestFrameMarshalJSON(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
initpc,
`^"github\.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+"$`,
}, {
0,
`^"unknown"$`,
}}
for i, tt := range tests {
got, err := json.Marshal(tt.Frame)
if err != nil {
t.Fatal(err)
}
if !regexp.MustCompile(tt.want).Match(got) {
t.Errorf("test %d: MarshalJSON:\n got %q\n want %q", i+1, string(got), tt.want)
}
}
}
10 changes: 10 additions & 0 deletions stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ func (f Frame) Format(s fmt.State, verb rune) {
}
}

// MarshalText formats a stacktrace Frame as a text string. The output is the
// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
func (f Frame) MarshalText() ([]byte, error) {
name := f.name()
if name == "unknown" {
return []byte(name), nil
}
return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
}

// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame

Expand Down

0 comments on commit 856c240

Please sign in to comment.