Skip to main content

Accumulate and inspect multiple errors

When you need to execute multiple operations and report on all of their failures, not just the first one, you can use go-multierror to accumulate the errors into a single error value.

Accumulating Errors and Checking for Failure

To begin collecting errors, use the multierror.Append function. You can start with a nil error and add new errors as they occur. After appending, you can use the ErrorOrNil method to check if any errors were actually collected. This method returns nil if no errors were appended, making it easy to integrate with standard Go error-checking patterns.

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")
}
}

The Append function returns an error that represents the collection of all appended errors. If you append only nil values, the result of ErrorOrNil() will be nil.

Inspecting Individual Errors

After accumulating errors, you might need to inspect the individual errors that occurred. The WrappedErrors method provides access to the underlying errors that were collected. It returns a slice of error values, which you can then iterate over or inspect as needed.

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")
}
}

Calling WrappedErrors on the accumulated error returns all the non-nil errors that were appended. This allows for more granular error handling, such as counting the number of errors or attempting to handle specific types of errors within the collection.