ut/errors.go

50 lines
1002 B
Go
Raw Normal View History

package ut
import (
"bytes"
"fmt"
)
var _ error = &Errors{}
// Errors exposes slice of errors.
type Errors struct {
Errs []error
}
func (e Errors) Error() string {
var msg = &bytes.Buffer{}
fmt.Fprint(msg, "errors: ")
for i, err := range e.Errs {
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 len(errs) > 0 {
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 &Errors{
Errs: errs,
}
}