Skip to content

Instantly share code, notes, and snippets.

@shazow
Last active September 18, 2016 17:26
Show Gist options
  • Save shazow/fa24c1d1a221c2f4997a4a942a9ebbdd to your computer and use it in GitHub Desktop.
Save shazow/fa24c1d1a221c2f4997a4a942a9ebbdd to your computer and use it in GitHub Desktop.
Yet another Go MultiError
package main
import (
"fmt"
"strings"
)
// MultiError implements the Error interface, can be checked as nil just like normal errors.
func MultiError() multiError {
var err multiError = nil
return err
}
type multiError []error
func (e *multiError) Add(err error) {
if err == nil {
return
}
if e == nil {
*e = []error{err}
return
}
*e = append(*e, err)
}
func (e multiError) Error() string {
if len(e) == 0 {
return ""
}
if len(e) == 1 {
return e[0].Error()
}
s := make([]string, 0, len(e)+1)
s = append(s, fmt.Sprintf("%d errors:", len(e)))
for _, err := range e {
s = append(s, " * "+err.Error())
}
return strings.Join(s, "\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment