add Cause function for gerror

This commit is contained in:
john
2019-07-09 10:40:26 +08:00
parent 8ff21d6936
commit 9ca9d6c4bd
3 changed files with 53 additions and 0 deletions

View File

@ -58,6 +58,16 @@ func Wrapf(err error, format string, args ...interface{}) error {
}
}
// Cause returns the root cause error.
func Cause(err error) error {
if err != nil {
if e, ok := err.(*Error); ok {
return e.Cause()
}
}
return err
}
// Stack returns the stack callers as string.
// It returns an empty string id the <err> does not support stacks.
func Stack(err error) string {

View File

@ -47,6 +47,23 @@ func (err *Error) Error() string {
return err.error.Error()
}
// Cause returns the root cause error.
func (err *Error) Cause() error {
loop := err
for loop != nil {
if loop.error != nil {
if e, ok := loop.error.(*Error); ok {
loop = e
} else {
return loop.error
}
} else {
return loop
}
}
return nil
}
// Format formats the frame according to the fmt.Formatter interface.
//
// %v, %s : Print the error string;

View File

@ -48,6 +48,32 @@ func Test_Wrap(t *testing.T) {
})
}
func Test_Cause(t *testing.T) {
gtest.Case(t, func() {
err := errors.New("1")
gtest.Assert(gerror.Cause(err), err)
})
gtest.Case(t, func() {
err := errors.New("1")
err = gerror.Wrap(err, "2")
err = gerror.Wrap(err, "3")
gtest.Assert(gerror.Cause(err), "1")
})
gtest.Case(t, func() {
err := gerror.New("1")
gtest.Assert(gerror.Cause(err), "1")
})
gtest.Case(t, func() {
err := gerror.New("1")
err = gerror.Wrap(err, "2")
err = gerror.Wrap(err, "3")
gtest.Assert(gerror.Cause(err), "1")
})
}
func Test_Format(t *testing.T) {
gtest.Case(t, func() {
err := errors.New("1")