packer: MultiError to represent multiple errors

This commit is contained in:
Mitchell Hashimoto 2013-05-22 13:36:09 -07:00
parent 09ca5be74f
commit 615f993de2
2 changed files with 56 additions and 0 deletions

24
packer/multi_error.go Normal file
View File

@ -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"))
}

View File

@ -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")
}