mirror of
https://gitee.com/johng/gf
synced 2026-06-06 02:25:47 +08:00
add Cause function for gerror
This commit is contained in:
@ -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 {
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -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")
|
||||
|
||||
Reference in New Issue
Block a user