From 856c240a51a2bf8fb8269ea7f3f9b046aadde36e Mon Sep 17 00:00:00 2001 From: Jonathan Hall Date: Sun, 17 Feb 2019 23:52:12 +0100 Subject: [PATCH] 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 --- json_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ stack.go | 10 ++++++++++ 2 files changed, 61 insertions(+) create mode 100644 json_test.go diff --git a/json_test.go b/json_test.go new file mode 100644 index 0000000..ad1adec --- /dev/null +++ b/json_test.go @@ -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) + } + } +} diff --git a/stack.go b/stack.go index 81f8856..779a834 100644 --- a/stack.go +++ b/stack.go @@ -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