Added function to build more useful error messages for debugging.

This commit is contained in:
Zach Klippenstein 2015-09-05 20:55:20 -07:00
parent 695e0af07b
commit a92512cf8f
2 changed files with 51 additions and 1 deletions

View file

@ -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()
}

26
util/error_test.go Normal file
View file

@ -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))
}