Skip to content

Instantly share code, notes, and snippets.

@ayanamist
Created May 28, 2022 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayanamist/f988de9c073ca7d07a29820621bdaeb3 to your computer and use it in GitHub Desktop.
Save ayanamist/f988de9c073ca7d07a29820621bdaeb3 to your computer and use it in GitHub Desktop.
Go errors: combine multiple errors into one
package util
import (
"errors"
"strings"
)
type combinedErr struct {
errs []error
}
func (c combinedErr) Error() string {
sb := &strings.Builder{}
for i, err := range c.errs {
if i > 0 {
sb.WriteString(": ")
}
sb.WriteString(err.Error())
}
return sb.String()
}
func (c combinedErr) Unwrap() error {
if len(c.errs) == 1 {
return nil
}
return combinedErr{errs: c.errs[1:]}
}
func (c combinedErr) Is(target error) bool {
for _, err := range c.errs {
if errors.Is(err, target) {
return true
}
}
return false
}
func (c combinedErr) As(target interface{}) bool {
for _, err := range c.errs {
if errors.As(err, target) {
return true
}
}
return false
}
func CombineErrors(errs ...error) error {
newErrs := make([]error, 0, len(errs))
for _, err := range errs {
if err != nil {
newErrs = append(newErrs, err)
}
}
if len(newErrs) == 0 {
return nil
}
return combinedErr{errs: newErrs}
}
package util
import (
stderrors "errors"
"fmt"
"testing"
)
func TestCombineErrors(t *testing.T) {
err1 := fmt.Errorf("error1")
err2 := fmt.Errorf("error2")
err3 := fmt.Errorf("error3")
err12 := CombineErrors(err1, err2)
if stderrors.Is(err12, err1) == false {
t.Errorf("errors.Is(err12, err1) should be true")
}
if stderrors.Is(err12, err2) == false {
t.Errorf("errors.Is(err12, err1) should be true")
}
if stderrors.Is(err12, err3) == true {
t.Errorf("errors.Is(err12, err1) should be false")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment