github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/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 every value in errs is nil.
    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  //
    14  // A non-nil error returned by Join implements the Unwrap() []error method.
    15  func Join(errs ...error) error {
    16  	n := 0
    17  	for _, err := range errs {
    18  		if err != nil {
    19  			n++
    20  		}
    21  	}
    22  	if n == 0 {
    23  		return nil
    24  	}
    25  	e := &joinError{
    26  		errs: make([]error, 0, n),
    27  	}
    28  	for _, err := range errs {
    29  		if err != nil {
    30  			e.errs = append(e.errs, err)
    31  		}
    32  	}
    33  	return e
    34  }
    35  
    36  type joinError struct {
    37  	errs []error
    38  }
    39  
    40  func (e *joinError) Error() string {
    41  	var b []byte
    42  	for i, err := range e.errs {
    43  		if i > 0 {
    44  			b = append(b, '\n')
    45  		}
    46  		b = append(b, err.Error()...)
    47  	}
    48  	return string(b)
    49  }
    50  
    51  func (e *joinError) Unwrap() []error {
    52  	return e.errs
    53  }