3 [![Build Status](http://img.shields.io/travis/hashicorp/go-multierror.svg?style=flat-square)][travis]
4 [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs]
6 [travis]: https://travis-ci.org/hashicorp/go-multierror
7 [godocs]: https://godoc.org/github.com/hashicorp/go-multierror
9 `go-multierror` is a package for Go that provides a mechanism for
10 representing a list of `error` values as a single `error`.
12 This allows a function in Go to return an `error` that might actually
13 be a list of errors. If the caller knows this, they can unwrap the
14 list and access the errors. If the caller doesn't know, the error
15 formats to a nice human-readable format.
17 `go-multierror` implements the
18 [errwrap](https://github.com/hashicorp/errwrap) interface so that it can
19 be used with that library, as well.
21 ## Installation and Docs
23 Install using `go get github.com/hashicorp/go-multierror`.
25 Full documentation is available at
26 http://godoc.org/github.com/hashicorp/go-multierror
30 go-multierror is easy to use and purposely built to be unobtrusive in
31 existing Go applications/libraries that may not be aware of it.
33 **Building a list of errors**
35 The `Append` function is used to create a list of errors. This function
36 behaves a lot like the Go built-in `append` function: it doesn't matter
37 if the first argument is nil, a `multierror.Error`, or any other `error`,
38 the function behaves as you would expect.
43 if err := step1(); err != nil {
44 result = multierror.Append(result, err)
46 if err := step2(); err != nil {
47 result = multierror.Append(result, err)
53 **Customizing the formatting of the errors**
55 By specifying a custom `ErrorFormat`, you can customize the format
56 of the `Error() string` function:
59 var result *multierror.Error
61 // ... accumulate errors here, maybe using Append
64 result.ErrorFormat = func([]error) string {
70 **Accessing the list of errors**
72 `multierror.Error` implements `error` so if the caller doesn't know about
73 multierror, it will work just fine. But if you're aware a multierror might
74 be returned, you can use type switches to access the list of errors:
77 if err := something(); err != nil {
78 if merr, ok := err.(*multierror.Error); ok {
84 **Returning a multierror only if there are errors**
86 If you build a `multierror.Error`, you can use the `ErrorOrNil` function
87 to return an `error` implementation only if there are errors to return:
90 var result *multierror.Error
92 // ... accumulate errors here
94 // Return the `error` only if errors were added to the multierror, otherwise
95 // return nil since there are no errors.
96 return result.ErrorOrNil()