github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/common/errors/multi_error.go (about)

     1  package errors
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  type multiError []error
     8  
     9  func (e multiError) Error() string {
    10  	var r strings.Builder
    11  	r.WriteString("multierr: ")
    12  	for _, err := range e {
    13  		r.WriteString(err.Error())
    14  		r.WriteString(" | ")
    15  	}
    16  	return r.String()
    17  }
    18  
    19  func Combine(maybeError ...error) error {
    20  	var errs multiError
    21  	for _, err := range maybeError {
    22  		if err != nil {
    23  			errs = append(errs, err)
    24  		}
    25  	}
    26  	if len(errs) == 0 {
    27  		return nil
    28  	}
    29  	return errs
    30  }
    31  
    32  func AllEqual(expected error, actual error) bool {
    33  	switch errs := actual.(type) {
    34  	case multiError:
    35  		if len(errs) == 0 {
    36  			return false
    37  		}
    38  		for _, err := range errs {
    39  			if err != expected {
    40  				return false
    41  			}
    42  		}
    43  		return true
    44  	default:
    45  		return errs == expected
    46  	}
    47  }