You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/errorx/batcherror.go

66 lines
1.0 KiB
Go

4 years ago
package errorx
import (
"bytes"
"sync"
)
4 years ago
type (
// A BatchError is an error that can hold multiple errors.
4 years ago
BatchError struct {
errs errorArray
lock sync.Mutex
4 years ago
}
errorArray []error
)
// Add adds errs to be, nil errors are ignored.
func (be *BatchError) Add(errs ...error) {
be.lock.Lock()
defer be.lock.Unlock()
for _, err := range errs {
if err != nil {
be.errs = append(be.errs, err)
}
4 years ago
}
}
// Err returns an error that represents all errors.
4 years ago
func (be *BatchError) Err() error {
be.lock.Lock()
defer be.lock.Unlock()
4 years ago
switch len(be.errs) {
case 0:
return nil
case 1:
return be.errs[0]
default:
return be.errs
}
}
// NotNil checks if any error inside.
4 years ago
func (be *BatchError) NotNil() bool {
be.lock.Lock()
defer be.lock.Unlock()
4 years ago
return len(be.errs) > 0
}
// Error returns a string that represents inside errors.
4 years ago
func (ea errorArray) Error() string {
var buf bytes.Buffer
for i := range ea {
if i > 0 {
buf.WriteByte('\n')
}
buf.WriteString(ea[i].Error())
}
return buf.String()
}