Skip to content

Fix uninitialized error detection #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
18 changes: 16 additions & 2 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func New(e interface{}) *Error {
// fmt.Errorf("%v"). 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 {
if e == nil {
if IsUninitialized(e) {
return nil
}

Expand Down Expand Up @@ -121,7 +121,7 @@ func Wrap(e interface{}, skip int) *Error {
// up 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 IsUninitialized(e) {
return nil
}

Expand Down Expand Up @@ -207,3 +207,17 @@ func (err *Error) TypeName() string {
func (err *Error) Unwrap() error {
return err.Err
}

// IsUninitialized returns true if the error is nil or is zero value
func IsUninitialized(i interface{}) bool {
if i == nil {
return true
}
switch reflect.TypeOf(i).Kind() {
case reflect.Struct:
return reflect.ValueOf(i).IsZero()
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(i).IsNil()
}
return false
}
39 changes: 39 additions & 0 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,42 @@ type errorString string
func (e errorString) Error() string {
return string(e)
}

type errorStruct struct {
message string
}

func (e errorStruct) Error() string {
return e.message
}

type errorStructPtr struct {
message string
}

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

func TestUninitializedErr(t *testing.T) {
var (
err = error(nil)
errStruct errorStruct
errStructPtr *errorStructPtr
)

err = WrapPrefix(err, "blah message", 0)
if err != (*Error)(nil) || !IsUninitialized(err) {
t.Errorf("Expected wrapped base error to be nil. Got %v", err)
}

err = WrapPrefix(errStruct, "blah message", 0)
if err != (*Error)(nil) || !IsUninitialized(err) {
t.Errorf("Expected wrapped errStruct to be nil. Got %v", err)
}

err = WrapPrefix(errStructPtr, "blah message", 0)
if err != (*Error)(nil) || !IsUninitialized(err) {
t.Errorf("Expected wrapped errStructPtr to be nil. Got %v", err)
}
}