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
|
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()
|
|
||||||
}
|
}
|
||||||
|
@ -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))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user