github.com/pavlo67/common@v0.5.3/common/errors/errors_multiple.go (about)

     1  package errors
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"strings"
     7  )
     8  
     9  // multipleErrors ------------------------------------------------------------------------------------------------
    10  
    11  type multipleErrors []error
    12  
    13  func (errs multipleErrors) String() string {
    14  	var errstrings []string
    15  	for _, err := range errs {
    16  		if err != nil {
    17  			errstring := err.Error()
    18  			if errstring == "" {
    19  				errstrings = append(errstrings, "???")
    20  			} else {
    21  				errstrings = append(errstrings, errstring)
    22  			}
    23  		}
    24  	}
    25  	return strings.Join(errstrings, " / ")
    26  }
    27  
    28  func (errs multipleErrors) Append(err error) multipleErrors {
    29  	if err != nil {
    30  		return append(errs, err)
    31  	}
    32  
    33  	return errs
    34  }
    35  
    36  func (errs multipleErrors) AppendErrs(errsToAppend multipleErrors) multipleErrors {
    37  	if len(errs) == 0 {
    38  		return errsToAppend
    39  	}
    40  
    41  	for _, err := range errsToAppend {
    42  		if err != nil {
    43  			errs = append(errs, err)
    44  		}
    45  	}
    46  
    47  	return errs
    48  }
    49  
    50  func (errs multipleErrors) Err() error {
    51  
    52  	// TODO!!! errs.Error() must keep Keyable interface
    53  
    54  	errstring := errs.String()
    55  	if errstring != "" {
    56  		return errors.New(errstring)
    57  	}
    58  
    59  	return nil
    60  }
    61  
    62  func (errs multipleErrors) MarshalJSON() ([]byte, error) {
    63  	messages := []string{}
    64  
    65  	for _, err := range errs {
    66  		if err != nil {
    67  			messages = append(messages, err.Error())
    68  		}
    69  	}
    70  
    71  	return json.Marshal(messages)
    72  }