Skip to content

Commit

Permalink
feat(errors): Added Group Errors (#106)
Browse files Browse the repository at this point in the history
Signed-off-by: Flc゛ <four_leaf_clover@foxmail.com>
  • Loading branch information
flc1125 authored Feb 18, 2024
1 parent dd935b4 commit 712bb5d
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
57 changes: 57 additions & 0 deletions errors/group.go
Original file line number Diff line number Diff line change
@@ -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]
}
29 changes: 29 additions & 0 deletions errors/group_test.go
Original file line number Diff line number Diff line change
@@ -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())
}

0 comments on commit 712bb5d

Please sign in to comment.