Skip to main content

Accumulate and inspect multiple errors

When you need to report multiple errors from a single function, standard Go error handling requires you to choose one, losing the others. The go-multierror package allows you to collect all errors from a series of operations and return them as a single error.

Accumulate Errors and Check for Existence

To collect errors, you can call multierror.Append, passing an initial error (often nil) and any subsequent errors you wish to combine. The function returns a result that you can check. To determine if any errors were actually accumulated, call the ErrorOrNil method on the result. This method returns nil if the result is empty, which is convenient for returning an error value from a function only when there is a problem.

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 Individual Errors

After accumulating errors, you may need to inspect the original errors that were combined. The WrappedErrors method provides access to the underlying errors by returning a slice of error ([]error). You can then iterate over this slice to examine each error individually, for example to check its type or log its message.

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