aboutsummaryrefslogtreecommitdiff
path: root/src/errors/join_test.go
diff options
context:
space:
mode:
authorDamien Neil <dneil@google.com>2022-09-22 10:43:26 -0700
committerDamien Neil <dneil@google.com>2022-09-29 18:40:40 +0000
commit4a0a2b33dfa3c99250efa222439f2c27d6780e4a (patch)
tree25b1d2541b1b1244fe86d3b7ab690bff475e7ac7 /src/errors/join_test.go
parent36f046d934c66fb6eb47d568e04665708c096ad7 (diff)
downloadgo-4a0a2b33dfa3c99250efa222439f2c27d6780e4a.tar.xz
errors, fmt: add support for wrapping multiple errors
An error which implements an "Unwrap() []error" method wraps all the non-nil errors in the returned []error. We replace the concept of the "error chain" inspected by errors.Is and errors.As with the "error tree". Is and As perform a pre-order, depth-first traversal of an error's tree. As returns the first matching result, if any. The new errors.Join function returns an error wrapping a list of errors. The fmt.Errorf function now supports multiple instances of the %w verb. For #53435. Change-Id: Ib7402e70b68e28af8f201d2b66bd8e87ccfb5283 Reviewed-on: https://go-review.googlesource.com/c/go/+/432898 Reviewed-by: Cherry Mui <cherryyz@google.com> Reviewed-by: Rob Pike <r@golang.org> Run-TryBot: Damien Neil <dneil@google.com> Reviewed-by: Joseph Tsai <joetsai@digital-static.net>
Diffstat (limited to 'src/errors/join_test.go')
-rw-r--r--src/errors/join_test.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/errors/join_test.go b/src/errors/join_test.go
new file mode 100644
index 0000000000..ee69314529
--- /dev/null
+++ b/src/errors/join_test.go
@@ -0,0 +1,49 @@
+// Copyright 2022 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package errors_test
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func TestJoinReturnsNil(t *testing.T) {
+ if err := errors.Join(); err != nil {
+ t.Errorf("errors.Join() = %v, want nil", err)
+ }
+ if err := errors.Join(nil); err != nil {
+ t.Errorf("errors.Join(nil) = %v, want nil", err)
+ }
+ if err := errors.Join(nil, nil); err != nil {
+ t.Errorf("errors.Join(nil, nil) = %v, want nil", err)
+ }
+}
+
+func TestJoin(t *testing.T) {
+ err1 := errors.New("err1")
+ err2 := errors.New("err2")
+ for _, test := range []struct {
+ errs []error
+ want []error
+ }{{
+ errs: []error{err1},
+ want: []error{err1},
+ }, {
+ errs: []error{err1, err2},
+ want: []error{err1, err2},
+ }, {
+ errs: []error{err1, nil, err2},
+ want: []error{err1, err2},
+ }} {
+ got := errors.Join(test.errs...).(interface{ Unwrap() []error }).Unwrap()
+ if !reflect.DeepEqual(got, test.want) {
+ t.Errorf("Join(%v) = %v; want %v", test.errs, got, test.want)
+ }
+ if len(got) != cap(got) {
+ t.Errorf("Join(%v) returns errors with len=%v, cap=%v; want len==cap", test.errs, len(got), cap(got))
+ }
+ }
+}