Skip to content

A Go (golang) package for representing a list of errors as a single error.

License

Notifications You must be signed in to change notification settings

mspiegel/go-multierror

 
 

Repository files navigation

go-multierror

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.

This is a fork of the hashicorp go-multierror library. In this fork, nil error values are handled transparently.

Installation and Docs

Install using go get github.com/mspiegel/go-multierror.

Usage

go-multierror is easy to use and purposely built to be unobtrusive in existing Go applications/libraries that may not be aware of it.

Building a list of errors

The Append function is used to create a list of errors. This function behaves a lot like the Go built-in append function: it doesn't matter if the first argument is nil, a multierror.Error, or any other error, the function behaves as you would expect.

var err, result error

err = step1()
result = multierror.Append(result, err)
err = step2()
result = multierror.Append(result, err)

return result

Customizing the formatting of the errors

By specifying a custom ErrorFormat, you can customize the format of the Error() string function:

var result *multierror.Error

// ... accumulate errors here, maybe using Append

if result != nil {
	result.ErrorFormat = func([]error) string {
		return "errors!"
	}
}

Accessing the list of errors

multierror.Error implements error so if the caller doesn't know about multierror, it will work just fine. But if you're aware a multierror might be returned, you can use type switches to access the list of errors:

if err := something(); err != nil {
	if merr, ok := err.(*multierror.Error); ok {
		// Use merr.Errors
	}
}

About

A Go (golang) package for representing a list of errors as a single error.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 91.5%
  • Makefile 8.5%