Add util to combine multiple errors so everyone checkable (#22473)

Signed-off-by: yah01 <yang.cen@zilliz.com>
This commit is contained in:
yah01 2023-02-28 19:35:47 +08:00 committed by GitHub
parent 60cd548bf5
commit 21eea923cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 0 deletions

View 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,
}
}

View 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))
}