From c6e9d39e7edd67a33a358ede111142d292cee283 Mon Sep 17 00:00:00 2001 From: wbflooksky <52812629+wbflooksky@users.noreply.github.com> Date: Wed, 19 May 2021 17:37:19 +0800 Subject: [PATCH] feat: feat func ExistStack(err error) bool: non-intrusive: Add a public method to determine if the error has been appended to the stack. Avoid adding the stack repeatedly for errors. fix: error method feat: test ExistStack add ExistStack test fix: error variable name style: optimizing code structure feat: add test example style(value): delete func reachable code style(build): edit format files --- errors.go | 21 +++++++++++++++++++++ errors_test.go | 20 ++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/errors.go b/errors.go index 161aea25..d740b8bb 100644 --- a/errors.go +++ b/errors.go @@ -106,6 +106,27 @@ func New(message string) error { } } +// ExistStack return an error already with stack +// ExistStack will check all parent error +func ExistStack(err error) bool { + type stackTracer interface { + StackTrace() StackTrace + } + _, ok := err.(stackTracer) + if ok { + return true + } + + type causer interface { + Cause() error + } + cause, ok := err.(causer) + if !ok { + return false + } + return ExistStack(cause.Cause()) +} + // Errorf formats according to a format specifier and returns the string // as a value that satisfies error. // Errorf also records the stack trace at the point it was called. diff --git a/errors_test.go b/errors_test.go index 2089b2f7..7da40e2a 100644 --- a/errors_test.go +++ b/errors_test.go @@ -27,6 +27,26 @@ func TestNew(t *testing.T) { } } +func TestExistStack(t *testing.T) { + tests := []struct { + err error + want bool + }{ + {io.EOF, false}, + {New("read error"), true}, + {Wrap(io.EOF, "read error"), true}, + {WithMessage(io.EOF, "read error"), false}, + {WithStack(io.EOF), true}, + } + + for _, tt := range tests { + got := ExistStack(tt.err) + if got != tt.want { + t.Errorf("ExistStack(%v): got: %v, want %v", tt.err, got, tt.want) + } + } +} + func TestWrapNil(t *testing.T) { got := Wrap(nil, "no error") if got != nil {