Accumulate and inspect multiple errors
To report on all failures from a series of operations, not just the first, you can use go-multierror to accumulate multiple errors. The multierror.Append function collects errors into a single error value.
After appending potential errors, use the ErrorOrNil method to check if any failures were actually collected. This method returns nil if the collection is empty, allowing it to be used in a standard if err != nil check. The following example accumulates two errors and confirms the result is not nil.
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")
}
}
Once you have determined that errors occurred, you can inspect them individually using the WrappedErrors method. This method returns a slice of error values, which you can then iterate over for logging or other processing.
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")
}
}
The []error slice returned by WrappedErrors contains the original errors, allowing you to access them for conditional logic or more detailed reporting.