mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-02-02 16:28:39 +08:00
refactor(core/errorx): use errors.Join simplify error handle (#4289)
This commit is contained in:
parent
ff6ee25d23
commit
8689a6247e
@ -1,7 +1,7 @@
|
||||
package errorx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"sync"
|
||||
)
|
||||
|
||||
@ -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 buf.String()
|
||||
return errors.Join(ea...).Error()
|
||||
}
|
||||
|
||||
// Unwrap combine the errors in the errorArray into a single error return
|
||||
func (ea errorArray) Unwrap() error {
|
||||
return errors.Join(ea...)
|
||||
}
|
||||
|
@ -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))
|
||||
})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user