Accumulate and inspect multiple errors
When a single logical operation involves multiple steps that can fail, you may need to report all failures instead of stopping at the first one. The go-multierror package facilitates this by collecting multiple error instances into a single error that can be returned to the caller.
Accumulating Errors
To accumulate errors, start with a nil error and call multierror.Append with any errors that occur. The Append function returns an error that collects all non-nil arguments. After all operations are complete, use the ErrorOrNil method on the result. This returns a standard nil if no errors were appended, ensuring your function correctly signals success in the absence of errors.
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")
}
}
Inspecting Individual Errors
To inspect the individual errors collected by multierror.Append, call the WrappedErrors method on the resulting error. This method returns a slice of the original error values that were accumulated. You can then iterate over this slice to handle each underlying error.
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")
}
}