diff --git a/packer/multi_error.go b/packer/multi_error.go new file mode 100644 index 000000000..3078bc075 --- /dev/null +++ b/packer/multi_error.go @@ -0,0 +1,24 @@ +package packer + +import ( + "fmt" + "strings" +) + +// MultiError is an error type to track multiple errors. This is used to +// accumulate errors in cases such as configuration parsing, and returning +// them as a single error. +type MultiError struct { + Errors []error +} + +func (e *MultiError) Error() string { + points := make([]string, len(e.Errors)) + for i, err := range e.Errors { + points[i] = fmt.Sprintf("* %s", err) + } + + return fmt.Sprintf( + "%d error(s) occurred:\n\n%s", + len(e.Errors), strings.Join(points, "\n")) +} diff --git a/packer/multi_error_test.go b/packer/multi_error_test.go new file mode 100644 index 000000000..f4965aac5 --- /dev/null +++ b/packer/multi_error_test.go @@ -0,0 +1,32 @@ +package packer + +import ( + "cgl.tideland.biz/asserts" + "errors" + "testing" +) + +func TestMultiError_Impl(t *testing.T) { + var raw interface{} + raw = &MultiError{} + if _, ok := raw.(error); !ok { + t.Fatal("MultiError must implement error") + } +} + +func TestMultiErrorError(t *testing.T) { + assert := asserts.NewTestingAsserts(t, true) + + expected := `2 error(s) occurred: + +* foo +* bar` + + errors := []error{ + errors.New("foo"), + errors.New("bar"), + } + + multi := &MultiError{errors} + assert.Equal(multi.Error(), expected, "should have proper error") +}