From 96b371837575bbda0e012539f5346411fcb9083e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Tue, 8 Aug 2023 12:38:22 +0200 Subject: [PATCH] v0.0.224 implement error.As(x) for exerr --- exerr/exerr.go | 72 +++++++++++++++++++++++++++++++++++++++++++++++++ goextVersion.go | 4 +-- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/exerr/exerr.go b/exerr/exerr.go index f423e06..0471d20 100644 --- a/exerr/exerr.go +++ b/exerr/exerr.go @@ -41,6 +41,24 @@ func (ee *ExErr) Is(e error) bool { return IsFrom(ee, e) } +// As must be implemented so that error.As(x) works +// +//goland:noinspection GoTypeAssertionOnErrors +func (ee *ExErr) As(e any) bool { + if dstErr, ok := e.(*ExErr); ok { + if dst0, ok := ee.contains(dstErr); ok { + dstErr = dst0 + return true + } else { + return false + } + } else if dstErr, ok := e.(error); ok { + return IsFrom(ee, dstErr) + } else { + return false + } +} + func (ee *ExErr) Log(evt *zerolog.Event) { evt.Msg(ee.FormatLog(LogPrintFull)) } @@ -196,6 +214,7 @@ func (ee *ExErr) RecursiveMeta(key string) *MetaValue { return nil } +// Depth returns the depth of recursively contained errors func (ee *ExErr) Depth() int { if ee.OriginalError == nil { return 1 @@ -204,6 +223,59 @@ func (ee *ExErr) Depth() int { } } +// contains test if the supplied error is contained in this error (anywhere in the chain) +func (ee *ExErr) contains(original *ExErr) (*ExErr, bool) { + if original == nil { + return nil, false + } + + if ee == original { + return ee, true + } + + for curr := ee; curr != nil; curr = curr.OriginalError { + if curr.equalsDirectProperties(curr) { + return curr, true + } + } + + return nil, false +} + +// equalsDirectProperties tests if ee and other are equals, but only looks at primary properties (not `OriginalError` or `Meta`) +func (ee *ExErr) equalsDirectProperties(other *ExErr) bool { + + if ee.UniqueID != other.UniqueID { + return false + } + if ee.Timestamp != other.Timestamp { + return false + } + if ee.Category != other.Category { + return false + } + if ee.Severity != other.Severity { + return false + } + if ee.Type != other.Type { + return false + } + if ee.StatusCode != other.StatusCode { + return false + } + if ee.Message != other.Message { + return false + } + if ee.WrappedErrType != other.WrappedErrType { + return false + } + if ee.Caller != other.Caller { + return false + } + + return true +} + func newID() string { return xid.New().String() } diff --git a/goextVersion.go b/goextVersion.go index 7b8831d..988f493 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.223" +const GoextVersion = "0.0.224" -const GoextVersionTimestamp = "2023-08-08T11:52:40+0200" +const GoextVersionTimestamp = "2023-08-08T12:38:22+0200"