ut/errors.go

55 lines
1.1 KiB
Go
Raw Normal View History

package ut
import (
"bytes"
"fmt"
)
var _ Errors = errorAggregate{}
// Errors exposes slice of errors.
type Errors interface {
error
Errs() []error
}
type errorAggregate []error
func (e errorAggregate) Errs() []error {
return e
}
func (e errorAggregate) Error() string {
var msg = &bytes.Buffer{}
fmt.Fprint(msg, "errors: ")
for i, err := range e {
if 0 < i {
fmt.Fprint(msg, "; ")
}
fmt.Fprint(msg, err)
}
return msg.String()
}
// ErrCombine combines one or more errors, nil entries are omitted and nil is returned if all given errors are nil. The first argument is expanded if it satisfies the Errors interface. In case of aggregation of errors the return error will satisfy the Errors interface.
func ErrCombine(errs ...error) error {
if 0 < len(errs) {
if e, ok := errs[0].(Errors); ok {
errs = append(e.Errs(), errs[1:]...)
}
}
for i := 0; i < len(errs); i++ {
if nil == errs[i] {
errs = append(errs[:i], errs[i+1:]...)
} else {
i++
}
}
if 0 == len(errs) {
return nil
} else if 1 == len(errs) {
return errs[0]
}
return errorAggregate(errs)
}