Skip to main content

Accumulate and inspect multiple errors

When you need to report more than one error from a function or a series of operations, you can accumulate them into a single error value. Use the multierror.Append function to collect errors as they occur.

After appending potential errors, use the ErrorOrNil method to determine if any errors were actually collected. This method returns nil if the accumulator is empty, and the error itself if it contains one or more errors. This allows the result to be used in a standard if err != nil check.

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 examine the specific errors that were accumulated, use the WrappedErrors method. This method returns a slice of error ([]error), giving you access to each individual error that was appended. You can then iterate over this slice to log, inspect, or 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")
}
}