github.com/andrewsun2898/u-root@v6.0.1-0.20200616011413-4b2895c1b815+incompatible/cmds/core/elvish/util/multierror.go (about)

     1  package util
     2  
     3  import "bytes"
     4  
     5  // MultiError pack multiple errors into one error.
     6  type MultiError struct {
     7  	Errors []error
     8  }
     9  
    10  func (es MultiError) Error() string {
    11  	switch len(es.Errors) {
    12  	case 0:
    13  		return "no error"
    14  	case 1:
    15  		return es.Errors[0].Error()
    16  	default:
    17  		var buf bytes.Buffer
    18  		buf.WriteString("multiple errors: ")
    19  		for i, e := range es.Errors {
    20  			if i > 0 {
    21  				buf.WriteString("; ")
    22  			}
    23  			buf.WriteString(e.Error())
    24  		}
    25  		return buf.String()
    26  	}
    27  }
    28  
    29  // Errors concatenate multiple errors into one. If all errors are nil, it
    30  // returns nil. If there is one non-nil error, it is returned. Otherwise the
    31  // return value is a MultiError containing all the non-nil arguments. Arguments
    32  // of the type MultiError are flattened.
    33  func Errors(errs ...error) error {
    34  	var nonNil []error
    35  	for _, err := range errs {
    36  		if err != nil {
    37  			if multi, ok := err.(MultiError); ok {
    38  				nonNil = append(nonNil, multi.Errors...)
    39  			} else {
    40  				nonNil = append(nonNil, err)
    41  			}
    42  		}
    43  	}
    44  	switch len(nonNil) {
    45  	case 0:
    46  		return nil
    47  	case 1:
    48  		return nonNil[0]
    49  	default:
    50  		return MultiError{nonNil}
    51  	}
    52  }