Skip to content

Commit

Permalink
Merge pull request #8 from tdakkota/feat/cause-method
Browse files Browse the repository at this point in the history
feat: add Cause function
  • Loading branch information
ernado committed Feb 21, 2022
2 parents 3d2f4f4 + cd0f0ab commit 916ae65
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
22 changes: 22 additions & 0 deletions cause_test.go
@@ -0,0 +1,22 @@
package errors

import (
"fmt"
"reflect"
"testing"
)

func TestCause(t *testing.T) {
err1 := fmt.Errorf("1")
erra := Wrap(err1, "wrap 2")
errb := Wrap(erra, "wrap3")

v, ok := Cause(errb)
if !ok {
t.Error("unexpected false")
return
}
if !reflect.DeepEqual(v, erra.(*wrapError).frame) {
t.Errorf("want %+v, got %+v", v, erra.(*wrapError).frame)
}
}
6 changes: 3 additions & 3 deletions frame.go
Expand Up @@ -25,10 +25,10 @@ func Caller(skip int) Frame {
return s
}

// location reports the file, line, and function of a frame.
// Location reports the file, line, and function of a frame.
//
// The returned function may be "" even if file and line are not.
func (f Frame) location() (function, file string, line int) {
func (f Frame) Location() (function, file string, line int) {
frames := runtime.CallersFrames(f.frames[:])
if _, ok := frames.Next(); !ok {
return "", "", 0
Expand All @@ -45,7 +45,7 @@ func (f Frame) location() (function, file string, line int) {
// after printing any other error detail.
func (f Frame) Format(p Printer) {
if p.Detail() {
function, file, line := f.location()
function, file, line := f.Location()
if function != "" {
p.Printf("%s\n ", function)
}
Expand Down
14 changes: 14 additions & 0 deletions wrap.go
Expand Up @@ -41,6 +41,20 @@ func Unwrap(err error) error {
return errors.Unwrap(err)
}

// Cause returns first recorded Frame.
func Cause(err error) (f Frame, r bool) {
for {
we, ok := err.(*wrapError)
if !ok {
return f, r
}
f = we.frame
r = r || ok

err = we.err
}
}

type wrapError struct {
msg string
err error
Expand Down

0 comments on commit 916ae65

Please sign in to comment.