mirror of
https://github.com/pkg/errors.git
synced 2025-04-27 13:12:40 +00:00
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
This commit is contained in:
parent
ffb6e22f01
commit
856c240a51
51
json_test.go
Normal file
51
json_test.go
Normal file
@ -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
stack.go
10
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
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user