Accumulate and inspect multiple errors
When you need to collect multiple errors during a process—such as validating several fields or performing a batch of independent operations—go-multierror provides a way to aggregate these into a single error value.
Accumulate errors with Append and ErrorOrNil
The Append function is the primary way to accumulate errors. It takes an existing error (which can be nil) and one or more new errors, returning a value that contains all non-nil errors. To verify if any errors were actually collected, use the ErrorOrNil method on the returned value.
package main
import (
"errors"
"github.com/hashicorp/go-multierror"
)
func main() {
first := errors.New("first")
second := errors.New("second")
result := multierror.Append(nil, first, second)
if result.ErrorOrNil() == nil {
panic("expected accumulated errors")
}
}
Inspect underlying errors with WrappedErrors
If you receive an accumulated error and need to access the individual errors it contains, use the WrappedErrors method. This method returns a slice of all the underlying errors that were accumulated. This allows you to programmatically inspect or iterate over the specific failures without relying on the formatted aggregate text.
package main
import (
"errors"
"github.com/hashicorp/go-multierror"
)
func main() {
result := multierror.Append(nil, errors.New("first"), errors.New("second"))
if len(result.WrappedErrors()) != 2 {
panic("expected two accumulated errors")
}
}