From 4a0a2b33dfa3c99250efa222439f2c27d6780e4a Mon Sep 17 00:00:00 2001 From: Damien Neil Date: Thu, 22 Sep 2022 10:43:26 -0700 Subject: 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 Reviewed-by: Rob Pike Run-TryBot: Damien Neil Reviewed-by: Joseph Tsai --- src/errors/errors_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/errors/errors_test.go') diff --git a/src/errors/errors_test.go b/src/errors/errors_test.go index cf4df90b69..8b93f530d5 100644 --- a/src/errors/errors_test.go +++ b/src/errors/errors_test.go @@ -51,3 +51,21 @@ func ExampleNew_errorf() { } // Output: user "bimmler" (id 17) not found } + +func ExampleJoin() { + err1 := errors.New("err1") + err2 := errors.New("err2") + err := errors.Join(err1, err2) + fmt.Println(err) + if errors.Is(err, err1) { + fmt.Println("err is err1") + } + if errors.Is(err, err2) { + fmt.Println("err is err2") + } + // Output: + // err1 + // err2 + // err is err1 + // err is err2 +} -- cgit v1.3