Skip to content

Commit

Permalink
Merge pull request #26 from srvc/izumin5210/slice
Browse files Browse the repository at this point in the history
Check error comparability for avoiding panic
  • Loading branch information
creasty committed Jan 14, 2020
2 parents c6bd1f3 + 4dc2444 commit 269c4c3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
12 changes: 10 additions & 2 deletions pkgerrors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fail

import (
"reflect"
"strings"

pkgerrors "github.com/pkg/errors"
Expand Down Expand Up @@ -79,8 +80,15 @@ func extractPkgError(err error) *pkgError {
break
}

if len(stackTraces) == 0 && rootErr == err {
return nil
if len(stackTraces) == 0 {
ret, et := reflect.TypeOf(rootErr), reflect.TypeOf(err)
if ret != nil && et != nil && ret.Comparable() && et.Comparable() {
if rootErr == err {
return nil
}
} else {
return nil
}
}

// Extract annotated messages by removing the trailing message.
Expand Down
28 changes: 28 additions & 0 deletions pkgerrors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fail

import (
"errors"
"strings"
"testing"

pkgerrors "github.com/pkg/errors"
Expand All @@ -20,6 +21,13 @@ func TestExtractPkgError(t *testing.T) {
assert.Nil(t, pkgErr)
})

t.Run("slice error", func(t *testing.T) {
err := errorSlice{errors.New("error")}

pkgErr := extractPkgError(err)
assert.Nil(t, pkgErr)
})

t.Run("pkg/errors.New", func(t *testing.T) {
err := pkgErrorsNew("message")

Expand Down Expand Up @@ -84,6 +92,16 @@ func TestExtractPkgError(t *testing.T) {
assert.NotEmpty(t, pkgErr.StackTrace)
assert.Equal(t, "pkgErrorsWrap", pkgErr.StackTrace[0].Func)
})

t.Run("with slice error", func(t *testing.T) {
err0 := errorSlice{errors.New("error")}
err1 := pkgErrorsWrap(err0, "message")

pkgErr := extractPkgError(err1)
assert.NotNil(t, pkgErr)
assert.Equal(t, err0, pkgErr.Err)
assert.NotEmpty(t, pkgErr.StackTrace)
})
})

t.Run("pkg/errors.WithMessage", func(t *testing.T) {
Expand Down Expand Up @@ -156,3 +174,13 @@ func pkgErrorsNew(msg string) error {
func pkgErrorsWrap(err error, msg string) error {
return pkgerrors.Wrap(err, msg)
}

type errorSlice []error

func (s errorSlice) Error() string {
msg := make([]string, len(s))
for i, e := range s {
msg[i] = e.Error()
}
return strings.Join(msg, ": ")
}

0 comments on commit 269c4c3

Please sign in to comment.