1package multierr
2
3// Copyright 2022 The Go Authors. All rights reserved.
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7// Join returns an error that wraps the given errors.
8// Any nil error values are discarded.
9// Join returns nil if errs contains no non-nil values.
10// The error formats as the concatenation of the strings obtained
11// by calling the Error method of each element of errs, with a newline
12// between each string.
13func Join(errs ...error) error {
14 n := 0
15 for _, err := range errs {
16 if err != nil {
17 n++
18 }
19 }
20 if n == 0 {
21 return nil
22 }
23 e := &joinError{
24 errs: make([]error, 0, n),
25 }
26 for _, err := range errs {
27 if err != nil {
28 e.errs = append(e.errs, err)
29 }
30 }
31 return e
32}
33
34type joinError struct {
35 errs []error
36}
37
38func (e *joinError) Error() string {
39 var b []byte
40 for i, err := range e.errs {
41 if i > 0 {
42 b = append(b, '\n')
43 }
44 b = append(b, err.Error()...)
45 }
46 return string(b)
47}
48
49func (e *joinError) Unwrap() []error {
50 return e.errs
51}