From 615f993de287cfdfde60c161c22c36fa36be5541 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Wed, 22 May 2013 13:36:09 -0700 Subject: [PATCH] packer: MultiError to represent multiple errors --- packer/multi_error.go | 24 ++++++++++++++++++++++++ packer/multi_error_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 packer/multi_error.go create mode 100644 packer/multi_error_test.go 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") +}