2022-01-05 05:15:38 -05:00
|
|
|
package multierr
|
|
|
|
|
|
|
|
import (
|
|
|
|
`fmt`
|
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
NewErrors returns a new MultiError (as an error) based on/initialized with a slice of error.Error (errs).
|
|
|
|
Any nil errors are trimmed.
|
|
|
|
If there are no actual errors after trimming, err will be nil.
|
|
|
|
*/
|
|
|
|
func NewErrors(errs ...error) (err error) {
|
|
|
|
|
|
|
|
if errs == nil || len(errs) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var realErrs []error = make([]error, 0)
|
|
|
|
|
|
|
|
for _, e := range errs {
|
|
|
|
if e == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
realErrs = append(realErrs, e)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(realErrs) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = &MultiError{
|
|
|
|
Errors: realErrs,
|
|
|
|
ErrorSep: "\n",
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewMultiError will provide a MultiError (true type), optionally initialized with errors.
|
|
|
|
func NewMultiError(errs ...error) (m *MultiError) {
|
|
|
|
|
2022-01-05 16:36:20 -05:00
|
|
|
var realErrs []error = make([]error, 0)
|
|
|
|
|
|
|
|
if errs != nil {
|
|
|
|
for _, e := range errs {
|
|
|
|
if e == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
realErrs = append(realErrs, e)
|
|
|
|
}
|
2022-01-05 05:15:38 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
m = &MultiError{
|
2022-01-05 16:36:20 -05:00
|
|
|
Errors: realErrs,
|
2022-01-05 05:15:38 -05:00
|
|
|
ErrorSep: "\n",
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error returns a string representation of a MultiError (to conform with the error interface).
|
|
|
|
func (e *MultiError) Error() (errStr string) {
|
|
|
|
|
|
|
|
var numErrs int
|
|
|
|
|
|
|
|
if e == nil || len(e.Errors) == 0 {
|
|
|
|
return
|
|
|
|
} else {
|
|
|
|
numErrs = len(e.Errors)
|
|
|
|
}
|
|
|
|
|
|
|
|
for idx, err := range e.Errors {
|
|
|
|
if (idx + 1) < numErrs {
|
|
|
|
errStr += fmt.Sprintf("%v%v", err.Error(), e.ErrorSep)
|
|
|
|
} else {
|
|
|
|
errStr += err.Error()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddError is a shorthand way of adding an error to a MultiError.
|
|
|
|
func (e *MultiError) AddError(err error) {
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
e.Errors = append(e.Errors, err)
|
|
|
|
|
|
|
|
}
|
2022-01-05 16:36:20 -05:00
|
|
|
|
|
|
|
// Count returns the number of errors in a MultiError.
|
|
|
|
func (e *MultiError) Count() (n int) {
|
|
|
|
|
|
|
|
n = len(e.Errors)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsEmpty is a shorthand for testing if e.Errors is empty.
|
|
|
|
func (e *MultiError) IsEmpty() (empty bool) {
|
|
|
|
|
|
|
|
if e.Count() == 0 {
|
|
|
|
empty = true
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|