2019-10-16 23:38:54 +02:00
|
|
|
package multierror
|
2019-10-05 18:35:46 +02:00
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
2021-08-11 20:13:28 +02:00
|
|
|
// MultiError type handles error accumulation from goroutines.
|
2019-10-05 18:35:46 +02:00
|
|
|
type MultiError struct {
|
|
|
|
Errors []error
|
|
|
|
mux sync.Mutex
|
|
|
|
}
|
|
|
|
|
2021-08-11 20:13:28 +02:00
|
|
|
// Error turns the MultiError structure into a string.
|
2019-10-05 18:35:46 +02:00
|
|
|
func (err *MultiError) Error() string {
|
|
|
|
str := ""
|
|
|
|
|
|
|
|
for _, e := range err.Errors {
|
|
|
|
str += e.Error() + "\n"
|
|
|
|
}
|
|
|
|
|
|
|
|
return str[:len(str)-1]
|
|
|
|
}
|
|
|
|
|
2021-08-11 20:13:28 +02:00
|
|
|
// Add adds an error to the Multierror structure.
|
2019-10-05 18:35:46 +02:00
|
|
|
func (err *MultiError) Add(e error) {
|
|
|
|
if e == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err.mux.Lock()
|
|
|
|
err.Errors = append(err.Errors, e)
|
|
|
|
err.mux.Unlock()
|
|
|
|
}
|
|
|
|
|
2019-10-09 16:15:36 +02:00
|
|
|
// Return is used as a wrapper on return on whether to return the
|
2021-08-11 20:13:28 +02:00
|
|
|
// MultiError Structure if errors exist or nil instead of delivering an empty structure.
|
2019-10-05 18:35:46 +02:00
|
|
|
func (err *MultiError) Return() error {
|
|
|
|
if len(err.Errors) > 0 {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|