Skip to content

Commit

Permalink
refactor(core/errorx): use errors.Join simplify error handle (#4289)
Browse files Browse the repository at this point in the history
  • Loading branch information
ch3nnn authored Aug 3, 2024
1 parent ff6ee25 commit 8689a62
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
16 changes: 6 additions & 10 deletions core/errorx/batcherror.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package errorx

import (
"bytes"
"errors"
"sync"
)

Expand Down Expand Up @@ -52,14 +52,10 @@ func (be *BatchError) NotNil() bool {

// Error returns a string that represents inside errors.
func (ea errorArray) Error() string {
var buf bytes.Buffer

for i := range ea {
if i > 0 {
buf.WriteByte('\n')
}
buf.WriteString(ea[i].Error())
}
return errors.Join(ea...).Error()
}

return buf.String()
// Unwrap combine the errors in the errorArray into a single error return
func (ea errorArray) Unwrap() error {
return errors.Join(ea...)
}
29 changes: 29 additions & 0 deletions core/errorx/batcherror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,32 @@ func TestBatchErrorConcurrentAdd(t *testing.T) {
assert.Equal(t, count, len(batch.errs))
assert.True(t, batch.NotNil())
}

func TestBatchError_Unwrap(t *testing.T) {
t.Run("nil", func(t *testing.T) {
var be BatchError
assert.Nil(t, be.Err())
assert.True(t, errors.Is(be.Err(), nil))
})

t.Run("one error", func(t *testing.T) {
var errFoo = errors.New("foo")
var errBar = errors.New("bar")
var be BatchError
be.Add(errFoo)
assert.True(t, errors.Is(be.Err(), errFoo))
assert.False(t, errors.Is(be.Err(), errBar))
})

t.Run("two errors", func(t *testing.T) {
var errFoo = errors.New("foo")
var errBar = errors.New("bar")
var errBaz = errors.New("baz")
var be BatchError
be.Add(errFoo)
be.Add(errBar)
assert.True(t, errors.Is(be.Err(), errFoo))
assert.True(t, errors.Is(be.Err(), errBar))
assert.False(t, errors.Is(be.Err(), errBaz))
})
}

0 comments on commit 8689a62

Please sign in to comment.