gitlab.com/jokerrs1/Sia@v1.3.2/build/errors.go (about)

     1  package build
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  )
     7  
     8  // ComposeErrors will take multiple errors and compose them into a single
     9  // errors with a longer message. Any nil errors used as inputs will be stripped
    10  // out, and if there are zero non-nil inputs then 'nil' will be returned.
    11  //
    12  // The original types of the errors is not preserved at all.
    13  func ComposeErrors(errs ...error) error {
    14  	// Strip out any nil errors.
    15  	var errStrings []string
    16  	for _, err := range errs {
    17  		if err != nil {
    18  			errStrings = append(errStrings, err.Error())
    19  		}
    20  	}
    21  
    22  	// Return nil if there are no non-nil errors in the input.
    23  	if len(errStrings) <= 0 {
    24  		return nil
    25  	}
    26  
    27  	// Combine all of the non-nil errors into one larger return value.
    28  	return errors.New(strings.Join(errStrings, "; "))
    29  }
    30  
    31  // ExtendErr will return a new error which extends the input error with a
    32  // string. If the input error is nil, then 'nil' will be returned, discarding
    33  // the input string.
    34  func ExtendErr(s string, err error) error {
    35  	if err == nil {
    36  		return nil
    37  	}
    38  	return errors.New(s + ": " + err.Error())
    39  }
    40  
    41  // JoinErrors concatenates the elements of errs to create a single error. The
    42  // separator string sep is placed between elements in the resulting error. Nil
    43  // errors are skipped. If errs is empty or only contains nil elements,
    44  // JoinErrors returns nil.
    45  func JoinErrors(errs []error, sep string) error {
    46  	var strs []string
    47  	for _, err := range errs {
    48  		if err != nil {
    49  			strs = append(strs, err.Error())
    50  		}
    51  	}
    52  	if len(strs) > 0 {
    53  		return errors.New(strings.Join(strs, sep))
    54  	}
    55  	return nil
    56  }