2020-07-26 17:09:05 +08:00
|
|
|
package errorx
|
|
|
|
|
|
2024-03-02 00:32:39 +08:00
|
|
|
import (
|
2024-08-03 11:00:59 +08:00
|
|
|
"errors"
|
2024-03-02 00:32:39 +08:00
|
|
|
"sync"
|
|
|
|
|
)
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2024-08-03 13:57:41 +08:00
|
|
|
// BatchError is an error that can hold multiple errors.
|
|
|
|
|
type BatchError struct {
|
|
|
|
|
errs []error
|
|
|
|
|
lock sync.RWMutex
|
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2024-08-03 13:57:41 +08:00
|
|
|
// Add adds one or more non-nil errors to the BatchError instance.
|
2022-02-15 18:40:26 +08:00
|
|
|
func (be *BatchError) Add(errs ...error) {
|
2024-03-02 00:59:15 +08:00
|
|
|
be.lock.Lock()
|
|
|
|
|
defer be.lock.Unlock()
|
2024-03-02 00:32:39 +08:00
|
|
|
|
2022-02-15 18:40:26 +08:00
|
|
|
for _, err := range errs {
|
|
|
|
|
if err != nil {
|
|
|
|
|
be.errs = append(be.errs, err)
|
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 13:57:41 +08:00
|
|
|
// Err returns an error that represents all accumulated errors.
|
|
|
|
|
// It returns nil if there are no errors.
|
2020-07-26 17:09:05 +08:00
|
|
|
func (be *BatchError) Err() error {
|
2024-08-03 13:57:41 +08:00
|
|
|
be.lock.RLock()
|
|
|
|
|
defer be.lock.RUnlock()
|
2024-03-02 00:59:15 +08:00
|
|
|
|
2024-08-03 13:57:41 +08:00
|
|
|
// If there are no non-nil errors, errors.Join(...) returns nil.
|
|
|
|
|
return errors.Join(be.errs...)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
|
2024-08-03 13:57:41 +08:00
|
|
|
// NotNil checks if there is at least one error inside the BatchError.
|
2020-07-26 17:09:05 +08:00
|
|
|
func (be *BatchError) NotNil() bool {
|
2024-08-03 13:57:41 +08:00
|
|
|
be.lock.RLock()
|
|
|
|
|
defer be.lock.RUnlock()
|
2024-03-02 00:59:15 +08:00
|
|
|
|
2020-07-26 17:09:05 +08:00
|
|
|
return len(be.errs) > 0
|
|
|
|
|
}
|