From 712bb5d396142125c3ae320a83b50ee1a2b071be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flc=E3=82=9B?= Date: Sun, 18 Feb 2024 11:19:41 +0800 Subject: [PATCH] feat(errors): Added `Group Errors` (#106) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Flcă‚› --- errors/group.go | 57 ++++++++++++++++++++++++++++++++++++++++++++ errors/group_test.go | 29 ++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 errors/group.go create mode 100644 errors/group_test.go diff --git a/errors/group.go b/errors/group.go new file mode 100644 index 00000000..d3955248 --- /dev/null +++ b/errors/group.go @@ -0,0 +1,57 @@ +package errors + +import "errors" + +var multipleErrors = "multiple errors" + +type Group struct { + errors []error +} + +func NewGroup() *Group { + return &Group{ + errors: make([]error, 0), + } +} + +func (g *Group) Add(errs ...error) *Group { + for _, err := range errs { + if err == nil { + continue + } + + g.errors = append(g.errors, err) + } + + return g +} + +func (g *Group) Error() string { + return multipleErrors +} + +func (g *Group) Errors() []error { + return g.errors +} + +func (g *Group) Len() int { + return len(g.errors) +} + +func (g *Group) Has(err error) bool { + for _, e := range g.errors { + if errors.Is(e, err) { + return true + } + } + + return false +} + +func (g *Group) First() error { + if len(g.errors) == 0 { + return nil + } + + return g.errors[0] +} diff --git a/errors/group_test.go b/errors/group_test.go new file mode 100644 index 00000000..1642d15f --- /dev/null +++ b/errors/group_test.go @@ -0,0 +1,29 @@ +package errors + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +var ( + err1 = errors.New("err1") + err2 = errors.New("err2") + err3 = errors.New("err3") +) + +func TestGroup(t *testing.T) { + g := NewGroup() + + assert.Equal(t, 0, g.Len()) + assert.Equal(t, g, g.Add(nil, err1, err2)) + + assert.Equal(t, 2, g.Len()) + assert.Equal(t, multipleErrors, g.Error()) + assert.Equal(t, []error{err1, err2}, g.Errors()) + assert.True(t, g.Has(err1)) + assert.True(t, g.Has(err2)) + assert.False(t, g.Has(err3)) + assert.Equal(t, err1, g.First()) +}