2020-06-29 19:21:03 +00:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2022-06-18 07:11:37 +00:00
|
|
|
"sync"
|
2020-06-29 19:21:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// ErrGroup accumulates multiple errors
|
|
|
|
// and produces single error message.
|
|
|
|
type ErrGroup struct {
|
2022-06-18 07:11:37 +00:00
|
|
|
mu sync.Mutex
|
2020-06-29 19:21:03 +00:00
|
|
|
errs []error
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add adds a new error to group.
|
2022-06-18 07:11:37 +00:00
|
|
|
// Is thread-safe.
|
2020-06-29 19:21:03 +00:00
|
|
|
func (eg *ErrGroup) Add(err error) {
|
2022-06-18 07:11:37 +00:00
|
|
|
eg.mu.Lock()
|
2020-06-29 19:21:03 +00:00
|
|
|
eg.errs = append(eg.errs, err)
|
2022-06-18 07:11:37 +00:00
|
|
|
eg.mu.Unlock()
|
2020-06-29 19:21:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Err checks if group contains at least
|
|
|
|
// one error.
|
|
|
|
func (eg *ErrGroup) Err() error {
|
2022-06-18 07:11:37 +00:00
|
|
|
if eg == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
eg.mu.Lock()
|
|
|
|
defer eg.mu.Unlock()
|
|
|
|
if len(eg.errs) == 0 {
|
2020-06-29 19:21:03 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return eg
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error satisfies Error interface
|
|
|
|
func (eg *ErrGroup) Error() string {
|
2022-06-18 07:11:37 +00:00
|
|
|
eg.mu.Lock()
|
|
|
|
defer eg.mu.Unlock()
|
|
|
|
|
2020-06-29 19:21:03 +00:00
|
|
|
if len(eg.errs) == 0 {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
var b strings.Builder
|
|
|
|
fmt.Fprintf(&b, "errors(%d): ", len(eg.errs))
|
|
|
|
for i, err := range eg.errs {
|
|
|
|
b.WriteString(err.Error())
|
|
|
|
if i != len(eg.errs)-1 {
|
|
|
|
b.WriteString("\n")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return b.String()
|
|
|
|
}
|