github.com/karrick/gorill@v1.10.3/errlist.go (about)

     1  package gorill
     2  
     3  import "strings"
     4  
     5  // ErrList is a slice of errors, useful when a function must return a single error, but has multiple
     6  // independent errors to return.
     7  type ErrList []error
     8  
     9  // Append appends non-nil errors to the list of errors.
    10  func (e *ErrList) Append(b error) {
    11  	if b != nil {
    12  		*e = append(*e, b)
    13  	}
    14  }
    15  
    16  // Count returns number of non-nil errors accumulated in ErrList.
    17  func (e ErrList) Count() int {
    18  	return len([]error(e))
    19  }
    20  
    21  // Err returns either a list of non-nil error values, or a single error value if the list only
    22  // contains one error.
    23  func (e ErrList) Err() error {
    24  	errors := make([]error, 0, len([]error(e)))
    25  	for _, e := range []error(e) {
    26  		if e != nil {
    27  			errors = append(errors, e)
    28  		}
    29  	}
    30  	switch len(errors) {
    31  	case 0:
    32  		return nil
    33  	case 1:
    34  		return e[0]
    35  	default:
    36  		return ErrList(errors)
    37  	}
    38  }
    39  
    40  // Error returns the string version of an error list, which is the list of errors, joined by a
    41  // comma-space byte sequence.
    42  func (e ErrList) Error() string {
    43  	es := make([]string, 0, len([]error(e)))
    44  	for i := range []error(e) {
    45  		if []error(e)[i] != nil {
    46  			es = append(es, []error(e)[i].Error())
    47  		}
    48  	}
    49  	return strings.Join(es, ", ")
    50  }