feat(influxd): Add errors.List to simplify capturing a list of errors

pull/12710/head
Stuart Carnie 2019-03-18 16:11:00 -07:00
parent 15c8151c52
commit 18d5d8c2f3
No known key found for this signature in database
GPG Key ID: 848D9C9718D78B4F
1 changed files with 59 additions and 0 deletions

59
kit/errors/list.go Normal file
View File

@ -0,0 +1,59 @@
package errors
import (
"errors"
"strings"
)
// List represents a list of errors.
type List struct {
errs []error
err error // cached error
}
// Append adds err to the errors list.
func (l *List) Append(err error) {
l.errs = append(l.errs, err)
l.err = nil
}
// AppendString adds a new error that formats as the given text.
func (l *List) AppendString(text string) {
l.errs = append(l.errs, errors.New(text))
l.err = nil
}
// Clear removes all the previously appended errors from the list.
func (l *List) Clear() {
for i := range l.errs {
l.errs[i] = nil
}
l.errs = l.errs[:0]
l.err = nil
}
// Err returns an error composed of the list of errors, separated by a new line, or nil if no errors
// were appended.
func (l *List) Err() error {
if len(l.errs) == 0 {
return nil
}
if l.err != nil {
switch len(l.errs) {
case 1:
l.err = l.errs[0]
default:
var sb strings.Builder
sb.WriteString(l.errs[0].Error())
for _, err := range l.errs[1:] {
sb.WriteRune('\n')
sb.WriteString(err.Error())
}
l.err = errors.New(sb.String())
}
}
return l.err
}