refactor(core/errorx): use errors.Join simplify error handle (#4289)

This commit is contained in:
chentong 2024-08-03 11:00:59 +08:00 committed by GitHub
parent ff6ee25d23
commit 8689a6247e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 11 deletions

View File

@ -1,7 +1,7 @@
package errorx package errorx
import ( import (
"bytes" "errors"
"sync" "sync"
) )
@ -52,14 +52,10 @@ func (be *BatchError) NotNil() bool {
// Error returns a string that represents inside errors. // Error returns a string that represents inside errors.
func (ea errorArray) Error() string { func (ea errorArray) Error() string {
var buf bytes.Buffer return errors.Join(ea...).Error()
}
for i := range ea {
if i > 0 { // Unwrap combine the errors in the errorArray into a single error return
buf.WriteByte('\n') func (ea errorArray) Unwrap() error {
} return errors.Join(ea...)
buf.WriteString(ea[i].Error())
}
return buf.String()
} }

View File

@ -66,3 +66,32 @@ func TestBatchErrorConcurrentAdd(t *testing.T) {
assert.Equal(t, count, len(batch.errs)) assert.Equal(t, count, len(batch.errs))
assert.True(t, batch.NotNil()) 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))
})
}