github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/packer/multi_error.go (about)

     1  package packer
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // MultiError is an error type to track multiple errors. This is used to
     9  // accumulate errors in cases such as configuration parsing, and returning
    10  // them as a single error.
    11  type MultiError struct {
    12  	Errors []error
    13  }
    14  
    15  func (e *MultiError) Error() string {
    16  	points := make([]string, len(e.Errors))
    17  	for i, err := range e.Errors {
    18  		points[i] = fmt.Sprintf("* %s", err)
    19  	}
    20  
    21  	return fmt.Sprintf(
    22  		"%d error(s) occurred:\n\n%s",
    23  		len(e.Errors), strings.Join(points, "\n"))
    24  }
    25  
    26  // MultiErrorAppend is a helper function that will append more errors
    27  // onto a MultiError in order to create a larger multi-error. If the
    28  // original error is not a MultiError, it will be turned into one.
    29  func MultiErrorAppend(err error, errs ...error) *MultiError {
    30  	if err == nil {
    31  		err = new(MultiError)
    32  	}
    33  
    34  	switch err := err.(type) {
    35  	case *MultiError:
    36  		if err == nil {
    37  			err = new(MultiError)
    38  		}
    39  
    40  		err.Errors = append(err.Errors, errs...)
    41  		return err
    42  	default:
    43  		newErrs := make([]error, len(errs)+1)
    44  		newErrs[0] = err
    45  		copy(newErrs[1:], errs)
    46  		return &MultiError{
    47  			Errors: newErrs,
    48  		}
    49  	}
    50  }