go-multierror
is a package for Go that provides a mechanism for representing a list of error
values as a single error
.
This allows a function in Go to return an error
that might actually be a list of errors. If the caller knows this, they can unwrap the list and access the errors. If the caller doesn’t know, the error formats to a nice human-readable format.
go-multierror
is fully compatible with the Go standard library errors package, including the functions As
, Is
, and Unwrap
. This provides a standardized approach for introspecting on error values.
Install using go get github.com/hashicorp/go-multierror
.
Usage
var result error
if err := step1(); err != nil {
result = multierror.Append(result, err)
}
if err := step2(); err != nil {
result = multierror.Append(result, err)
}
return result
Returning a multierror only if there are errors
var result *multierror.Error
// ... accumulate errors here
// Return the `error` only if errors were added to the multierror, otherwise
// return nil since there are no errors.
return result.ErrorOrNil()