Skip to content

Instantly share code, notes, and snippets.

@grahamking
Created May 22, 2020 17:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save grahamking/51beb2bc5ae8fbbc06ae7341f3381d64 to your computer and use it in GitHub Desktop.
Save grahamking/51beb2bc5ae8fbbc06ae7341f3381d64 to your computer and use it in GitHub Desktop.
Collect and handle multiple errors in Go
package util
import (
"errors"
"strings"
)
// Errs is an error that collects other errors, for when you want to do
// several things and then report all of them.
type Errs struct {
errors []error
}
func (e *Errs) Add(err error) {
if err != nil {
e.errors = append(e.errors, err)
}
}
func (e *Errs) Ret() error {
if e == nil || e.IsEmpty() {
return nil
}
return e
}
func (e *Errs) IsEmpty() bool {
return e.Len() == 0
}
func (e *Errs) Len() int {
return len(e.errors)
}
func (e *Errs) Error() string {
asStr := make([]string, len(e.errors))
for i, x := range e.errors {
asStr[i] = x.Error()
}
return strings.Join(asStr, ". ")
}
func (e *Errs) Is(target error) bool {
for _, candidate := range e.errors {
if errors.Is(candidate, target) {
return true
}
}
return false
}
func (e *Errs) As(target interface{}) bool {
for _, candidate := range e.errors {
if errors.As(candidate, target) {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment