From 6d6e33d3c71f942b218cf3e48a5707d59863a15a Mon Sep 17 00:00:00 2001 From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Mon, 28 Nov 2022 21:22:23 +0800 Subject: [PATCH] errors --- errors/errors.go | 40 ++++++++++++++++++++++++++++++++++++++++ errors/errors_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 errors/errors.go create mode 100644 errors/errors_test.go diff --git a/errors/errors.go b/errors/errors.go new file mode 100644 index 0000000..86045de --- /dev/null +++ b/errors/errors.go @@ -0,0 +1,40 @@ +package errors + +type Error struct { + son interface{} + reason string + action string +} + +func (t Error) Error() string { + return t.reason +} + +func Catch(e error, action string) bool { + if v, ok := e.(Error); ok { + if v.action == action { + return true + } else if v.son != nil { + return Catch((v.son).(Error), action) + } + } + return false +} + +func Grow(e error, son Error) Error { + if v, ok := e.(Error); ok { + son.son = v + } else { + son.son = Error{ + reason: v.Error(), + } + } + return son +} + +func New(reason string, action string) Error { + return Error{ + reason: reason, + action: action, + } +} diff --git a/errors/errors_test.go b/errors/errors_test.go new file mode 100644 index 0000000..885baa4 --- /dev/null +++ b/errors/errors_test.go @@ -0,0 +1,27 @@ +package errors + +import "testing" + +func TestXxx(t *testing.T) { + var err error + + err = New("r0", "a0") + + if !Catch(err, "a0") { + t.Fail() + } + + if Catch(err, "a1") { + t.Fail() + } + + err = Grow(err, New("r1", "a1")) + + if !Catch(err, "a0") { + t.Fail() + } + + if !Catch(err, "a1") { + t.Fail() + } +} -- 2.39.2