github.com/alloyzeus/go-azfl@v0.0.0-20231220071816-9740126a2d07/errors/set.go (about)

     1  package errors
     2  
     3  import "strings"
     4  
     5  // ErrorSet is an abstraction for an error that holds multiple errors. This
     6  // is usually used for operations that collects all errors before returning.
     7  type ErrorSet interface {
     8  	error
     9  	Errors() []error
    10  }
    11  
    12  // UnwrapErrorSet returns the contained error instances if err is
    13  // indeed a ErrorSet.
    14  func UnwrapErrorSet(err error) []error {
    15  	if errSet := asErrorSet(err); errSet != nil {
    16  		return errSet.Errors()
    17  	}
    18  	return nil
    19  }
    20  
    21  // asErrorSet returns err as an ErrorSet if err is indeed an ErrorSet,
    22  // otherwise it returns nil.
    23  func asErrorSet(err error) ErrorSet {
    24  	e, _ := err.(ErrorSet)
    25  	return e
    26  }
    27  
    28  func Set(errs ...error) ErrorSet { return errorSet(errs) }
    29  
    30  type errorSet []error
    31  
    32  var (
    33  	_ error    = errorSet{}
    34  	_ ErrorSet = errorSet{}
    35  )
    36  
    37  func (e errorSet) Error() string {
    38  	if len(e) > 0 {
    39  		errs := make([]string, 0, len(e))
    40  		for _, ce := range e {
    41  			errs = append(errs, ce.Error())
    42  		}
    43  		s := strings.Join(errs, ", ")
    44  		if s != "" {
    45  			return s
    46  		}
    47  	}
    48  	return ""
    49  }
    50  
    51  func (e errorSet) Errors() []error { return e }