Source file src/errors/join.go

     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  import (
     8  	"unsafe"
     9  )
    10  
    11  // Join returns an error that wraps the given errors.
    12  // Any nil error values are discarded.
    13  // Join returns nil if every value in errs is nil.
    14  // The error formats as the concatenation of the strings obtained
    15  // by calling the Error method of each element of errs, with a newline
    16  // between each string.
    17  //
    18  // A non-nil error returned by Join implements the Unwrap() []error method.
    19  // The errors may be inspected with [Is] and [As].
    20  func Join(errs ...error) error {
    21  	n := 0
    22  	for _, err := range errs {
    23  		if err != nil {
    24  			n++
    25  		}
    26  	}
    27  	if n == 0 {
    28  		return nil
    29  	}
    30  	e := &joinError{
    31  		errs: make([]error, 0, n),
    32  	}
    33  	for _, err := range errs {
    34  		if err != nil {
    35  			e.errs = append(e.errs, err)
    36  		}
    37  	}
    38  	return e
    39  }
    40  
    41  type joinError struct {
    42  	errs []error
    43  }
    44  
    45  func (e *joinError) Error() string {
    46  	// Since Join returns nil if every value in errs is nil,
    47  	// e.errs cannot be empty.
    48  	if len(e.errs) == 1 {
    49  		return e.errs[0].Error()
    50  	}
    51  
    52  	b := []byte(e.errs[0].Error())
    53  	for _, err := range e.errs[1:] {
    54  		b = append(b, '\n')
    55  		b = append(b, err.Error()...)
    56  	}
    57  	// At this point, b has at least one byte '\n'.
    58  	return unsafe.String(&b[0], len(b))
    59  }
    60  
    61  func (e *joinError) Unwrap() []error {
    62  	return e.errs
    63  }
    64  

View as plain text