Accumulate and inspect multiple errors
Accumulating multiple errors in go-multierror allows you to collect failures across several operations and return them as a single result. By using multierror.Append, you can combine individual errors into a structured container that supports standard Go error handling patterns.
Accumulate errors and verify results
When performing a series of tasks, you can use multierror.Append to collect any errors that occur. The function handles nil values gracefully, only adding non-nil errors to the collection. After all operations are complete, ErrorOrNil provides a convenient way to return either the accumulated errors or nil if no errors were found.
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
To programmatically inspect the specific errors contained within a multierror, use the WrappedErrors method. This method returns a slice of all accumulated errors, allowing you to verify the contents without parsing the formatted error string. WrappedErrors is nil-safe and will return a nil slice if called on a nil multierror.
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")
}
}
Key behaviors
- Flattening:
multierror.Appendautomatically flattens nested multierrors. If you append one multierror to another, the individual errors from the source are added directly to the destination's list. - Nil Safety: You can pass a
nilerror as the first argument tomultierror.Append; it will initialize a new multierror container for you. - Interface Compatibility: The value returned by
multierror.Appendimplements the standard Goerrorinterface. UsingErrorOrNilensures that you return a truenilinterface value when no errors are present, preventing common Go gotchas where a non-nil interface points to a nil concrete type.