github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/errors/join.go (about) 1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package errors 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. 13 func 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 34 type joinError struct { 35 errs []error 36 } 37 38 func (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 49 func (e *joinError) Unwrap() []error { 50 return e.errs 51 }