diff --git a/util/error.go b/util/error.go index 2ddeafc..e065899 100644 --- a/util/error.go +++ b/util/error.go @@ -1,6 +1,9 @@ package util -import "fmt" +import ( + "bytes" + "fmt" +) /* Err is the implementation of error that all goadb functions return. @@ -118,3 +121,24 @@ func HasErrCode(err error, code ErrCode) bool { return false } } + +/* +ErrorWithCauseChain formats err and all its causes if it's an *Err, else returns +err.Error(). +*/ +func ErrorWithCauseChain(err error) string { + var buffer bytes.Buffer + + for { + if wrappedErr, ok := err.(*Err); ok && wrappedErr.Cause != nil { + fmt.Fprintln(&buffer, wrappedErr.Error()) + fmt.Fprint(&buffer, "caused by ") + err = wrappedErr.Cause + } else { + break + } + } + buffer.WriteString(err.Error()) + + return buffer.String() +} diff --git a/util/error_test.go b/util/error_test.go new file mode 100644 index 0000000..2e629db --- /dev/null +++ b/util/error_test.go @@ -0,0 +1,26 @@ +package util + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestErrorWithCauseChain(t *testing.T) { + err := &Err{ + Message: "err1", + Code: AssertionError, + Cause: &Err{ + Message: "err2", + Code: AssertionError, + Cause: errors.New("err3"), + }, + } + + expected := `AssertionError: err1 +caused by AssertionError: err2 +caused by err3` + + assert.Equal(t, expected, ErrorWithCauseChain(err)) +}