mirror of
https://gitee.com/milvus-io/milvus.git
synced 2026-01-07 19:31:51 +08:00
Add util to combine multiple errors so everyone checkable (#22473)
Signed-off-by: yah01 <yang.cen@zilliz.com>
This commit is contained in:
parent
60cd548bf5
commit
21eea923cc
37
internal/util/errutil/errors.go
Normal file
37
internal/util/errutil/errors.go
Normal file
@ -0,0 +1,37 @@
|
||||
package errutil
|
||||
|
||||
import "github.com/cockroachdb/errors"
|
||||
|
||||
type multiErrors struct {
|
||||
errs []error
|
||||
}
|
||||
|
||||
func (e multiErrors) Unwrap() error {
|
||||
if len(e.errs) <= 1 {
|
||||
return nil
|
||||
}
|
||||
return multiErrors{
|
||||
errs: e.errs[1:],
|
||||
}
|
||||
}
|
||||
|
||||
func (e multiErrors) Error() string {
|
||||
final := e.errs[0]
|
||||
for i := 1; i < len(e.errs); i++ {
|
||||
final = errors.Wrap(e.errs[i], final.Error())
|
||||
}
|
||||
return final.Error()
|
||||
}
|
||||
|
||||
func (e multiErrors) Is(err error) bool {
|
||||
return errors.IsAny(err, e.errs...)
|
||||
}
|
||||
|
||||
func Combine(errs ...error) error {
|
||||
if len(errs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return multiErrors{
|
||||
errs,
|
||||
}
|
||||
}
|
||||
31
internal/util/errutil/errors_test.go
Normal file
31
internal/util/errutil/errors_test.go
Normal file
@ -0,0 +1,31 @@
|
||||
package errutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/cockroachdb/errors"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type ErrSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func (s *ErrSuite) TestCombine() {
|
||||
var (
|
||||
errFirst = errors.New("first")
|
||||
errSecond = errors.New("second")
|
||||
errThird = errors.New("third")
|
||||
)
|
||||
|
||||
err := Combine(errFirst, errSecond)
|
||||
s.True(errors.Is(err, errFirst))
|
||||
s.True(errors.Is(err, errSecond))
|
||||
s.False(errors.Is(err, errThird))
|
||||
|
||||
s.Equal("first: second", err.Error())
|
||||
}
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
suite.Run(t, new(ErrSuite))
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user