github.com/opentelekomcloud/gophertelekomcloud@v0.9.3/internal/multierr/multierr.go (about)

     1  // Package multierr contains simple implementation of multiple error handling.
     2  // Inspired by https://github.com/hashicorp/go-multierror.
     3  package multierr
     4  
     5  import (
     6  	"errors"
     7  	"fmt"
     8  	"strings"
     9  )
    10  
    11  // MultiError is container for multiple errors.
    12  type MultiError []error
    13  
    14  // Error returns an error message.
    15  func (m MultiError) Error() string {
    16  	errorMessages := make([]string, 0, len(m))
    17  
    18  	for _, err := range m {
    19  		// can contain nil errors
    20  		if err != nil {
    21  			errorMessages = append(errorMessages, err.Error())
    22  		}
    23  	}
    24  
    25  	switch len(errorMessages) {
    26  	case 0:
    27  		return ""
    28  	case 1:
    29  		return errorMessages[0]
    30  	default:
    31  		return fmt.Sprintf("multiple errors returned:\n\t%s", strings.Join(errorMessages, ",\n\t"))
    32  	}
    33  }
    34  
    35  // ErrorOrNil returns nil in case there are no errors inside.
    36  func (m MultiError) ErrorOrNil() error {
    37  	if m.Error() == "" {
    38  		return nil
    39  	}
    40  
    41  	return m
    42  }
    43  
    44  // Is validates whenever any of included errors Is target error.
    45  func (m MultiError) Is(target error) bool {
    46  	if target == nil {
    47  		return false
    48  	}
    49  
    50  	for _, err := range m {
    51  		if errors.Is(err, target) {
    52  			return true
    53  		}
    54  	}
    55  
    56  	return false
    57  }