Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
21 changes: 19 additions & 2 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,25 @@ func New(e interface{}) *Error {
// explicitly wrap an *Error with a new stacktrace use Errorf. The skip
// parameter indicates how far up the stack to start the stacktrace. 0 is from
// the current call, 1 from its caller, etc.
func Wrap(e interface{}, skip int) *Error {

// isNil reports whether e is a nil interface value or a typed nil
// (nil pointer/slice/map/func/chan/interface). Zero-value structs that
// implement error are not considered nil.
func isNil(e interface{}) bool {
if e == nil {
return true
}
v := reflect.ValueOf(e)
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
return v.IsNil()
default:
return false
}
}

func Wrap(e interface{}, skip int) *Error {
if isNil(e) {
return nil
}

Expand Down Expand Up @@ -127,7 +144,7 @@ func Wrap(e interface{}, skip int) *Error {
// the stack to start the stacktrace. 0 is from the current call, 1 from its
// caller, etc.
func WrapPrefix(e interface{}, prefix string, skip int) *Error {
if e == nil {
if isNil(e) {
return nil
}

Expand Down
21 changes: 21 additions & 0 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,24 @@ type errorString string
func (e errorString) Error() string {
return string(e)
}

type typedNilError struct{ message string }

func (e *typedNilError) Error() string { return e.message }

func TestWrapTypedNil(t *testing.T) {
var ptr *typedNilError
if Wrap(ptr, 0) != nil {
t.Errorf("Wrap typed nil pointer should return nil")
}
if WrapPrefix(ptr, "prefix", 0) != nil {
t.Errorf("WrapPrefix typed nil pointer should return nil")
}
if Wrap(nil, 0) != nil || WrapPrefix(nil, "p", 0) != nil {
t.Errorf("Wrap/WrapPrefix nil should return nil")
}
nonNil := &typedNilError{message: "x"}
if Wrap(nonNil, 0) == nil {
t.Errorf("Wrap non-nil pointer should wrap")
}
}