Skip to content

Commit

Permalink
Merge pull request #10 from kanmu/top_frame
Browse files Browse the repository at this point in the history
Add TopFrame function
  • Loading branch information
kazukousen committed Jan 9, 2024
2 parents 4a500fe + 0073343 commit 70994c6
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
21 changes: 21 additions & 0 deletions frame.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,27 @@ import (
"github.com/pkg/errors"
)

type ErrorSets []ErrorSet

func (es ErrorSets) TopFrame() *Frame {
if len(es) == 0 {
return nil
} else if len(es[0].Frames) == 0 {
return nil
}

top := es[0].Frames

if p := es[0].Parent; p != nil {
top = top.Exclude(p)
}
if len(top) == 0 {
return nil
}

return top[0]
}

type ErrorSet struct {
Error error
Frames Frames
Expand Down
10 changes: 5 additions & 5 deletions pperr.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,16 @@ func Fprint(w io.Writer, err error) {
}

func FprintFunc(w io.Writer, err error, puts Printer) {
for _, e := range extractErrorSet(err, nil) {
for _, e := range extractErrorSets(err, nil) {
puts(w, e.Error, e.Frames, e.Parent)
}
}

func ExtractErrorSet(err error) []ErrorSet {
return extractErrorSet(err, nil)
func ExtractErrorSets(err error) ErrorSets {
return extractErrorSets(err, nil)
}

func extractErrorSet(err error, parent Frames) []ErrorSet {
func extractErrorSets(err error, parent Frames) []ErrorSet {
if err == nil {
return nil
}
Expand All @@ -70,7 +70,7 @@ func extractErrorSet(err error, parent Frames) []ErrorSet {
causeParent = parent
}

if es := extractErrorSet(withCause.Unwrap(), causeParent); es != nil {
if es := extractErrorSets(withCause.Unwrap(), causeParent); es != nil {
errs = es
}
}
Expand Down
6 changes: 3 additions & 3 deletions pperr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ func f3(native bool) error {
}
}

func TestExtractErrorSet(t *testing.T) {
func TestExtractErrorSets(t *testing.T) {
assert := assert.New(t)

err := f1(true)

var buf strings.Builder
for _, e := range pperr.ExtractErrorSet(err) {
for _, e := range pperr.ExtractErrorSets(err) {
pperr.DefaultPrinter(&buf, e.Error, e.Frames, e.Parent)
}
actual := buf.String()
Expand Down Expand Up @@ -76,7 +76,7 @@ syscall.Errno: no such file or directory
*errors.withStack: from f1(): from f2(): from f21(): from f23: from f3(): open not_found: no such file or directory
github.com/kanmu/pperr_test.f1
.../pperr_test.go:NN
github.com/kanmu/pperr_test.TestExtractErrorSet
github.com/kanmu/pperr_test.TestExtractErrorSets
.../pperr_test.go:NN
testing.tRunner
.../go/...:NN
Expand Down

0 comments on commit 70994c6

Please sign in to comment.