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

Add json.Marshaler support to the Frame type. #197

Merged
merged 4 commits into from
Feb 17, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package errors

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

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+"$`,
flimzy marked this conversation as resolved.
Show resolved Hide resolved
}, {
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)
}
}
}
13 changes: 13 additions & 0 deletions stack.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package errors

import (
"encoding/json"
"fmt"
"io"
"path"
Expand Down Expand Up @@ -83,6 +84,18 @@ func (f Frame) Format(s fmt.State, verb rune) {
}
}

// MarshalJSON formats a stacktrace Frame for easy inclusion in JSON stack
// traces. The format is the same as that of fmt.Format("%+v"), but without
// newlines or tabs.
func (f Frame) MarshalJSON() ([]byte, error) {
flimzy marked this conversation as resolved.
Show resolved Hide resolved
name := f.name()
if name == "unknown" {
return json.Marshal(name)
}
str := fmt.Sprintf("%s %s:%d", name, f.file(), f.line())
return json.Marshal(str)
}

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

Expand Down