util/multierr: add Range (#6643)

Errors in Go are no longer viewed as a linear chain, but a tree.
See golang/go#53435.

Add a Range function that iterates through an error
in a pre-order, depth-first order.
This matches the iteration order of errors.As in Go 1.20.

This adds the logic (but currently commented out) for having
Error implement the multi-error version of Unwrap in Go 1.20.
It is commented out currently since it causes "go vet"
to complain about having the "wrong" signature.

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai
2022-12-12 16:48:11 -08:00
committed by GitHub
parent 041a0e3c27
commit c47578b528
2 changed files with 76 additions and 1 deletions

View File

@@ -6,9 +6,11 @@ package multierr_test
import (
"errors"
"fmt"
"testing"
qt "github.com/frankban/quicktest"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"tailscale.com/util/multierr"
)
@@ -78,3 +80,29 @@ func TestAll(t *testing.T) {
C.Assert(ee.Is(x), qt.IsFalse)
}
}
func TestRange(t *testing.T) {
C := qt.New(t)
errA := errors.New("A")
errB := errors.New("B")
errC := errors.New("C")
errD := errors.New("D")
errCD := multierr.New(errC, errD)
errCD1 := fmt.Errorf("1:%w", errCD)
errE := errors.New("E")
errE1 := fmt.Errorf("1:%w", errE)
errE2 := fmt.Errorf("2:%w", errE1)
errF := errors.New("F")
root := multierr.New(errA, errB, errCD1, errE2, errF)
var got []error
want := []error{root, errA, errB, errCD1, errCD, errC, errD, errE2, errE1, errE, errF}
multierr.Range(root, func(err error) bool {
got = append(got, err)
return true
})
C.Assert(got, qt.CmpEquals(cmp.Comparer(func(x, y error) bool {
return x.Error() == y.Error()
})), want)
}