Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Created January 14, 2022 19:27
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 imjasonh/e02fc9cb2f06dba57924a3f104b58649 to your computer and use it in GitHub Desktop.
Save imjasonh/e02fc9cb2f06dba57924a3f104b58649 to your computer and use it in GitHub Desktop.
multierr without multierr
// You can edit this code!
// Click here and start typing.
package main
import (
"errors"
"fmt"
)
var myerr = errors.New("error!")
func main() {
errs := []error{
myerr,
nil, nil, nil,
myerr,
nil, nil,
myerr,
myerr,
nil,
}
// Filter errs in-place.
n := 0
for _, e := range errs {
if e != nil {
errs[n] = e
n++
}
}
errs = errs[:n]
// Collapse into a single error.
var err error
if len(errs) == 0 {
err = nil
} else if len(errs) == 1 {
err = errs[0]
} else {
err = fmt.Errorf("%s; %w", errs[:len(errs)-1], errs[len(errs)-1])
}
fmt.Println(err)
fmt.Println(errors.Is(err, myerr))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment