Extensions for the standard errors
package.
Go 1.21+
go get go-simpler.org/errorsx
A multi-target version of errors.Is
.
// Before:
if errors.Is(err, os.ErrNotExist) || errors.Is(err, os.ErrPermission) {
fmt.Println(err)
}
// After:
if errorsx.IsAny(err, os.ErrNotExist, os.ErrPermission) {
fmt.Println(err)
}
A generic version of errors.As
.
// Before:
var pathErr *os.PathError
if errors.As(err, &pathErr) {
fmt.Println(pathErr.Path)
}
// After:
if pathErr, ok := errorsx.As[*os.PathError](err); ok {
fmt.Println(pathErr.Path)
}
Attempts to close the given io.Closer
and assigns the returned error (if any) to err
.
f, err := os.Open("file.txt")
if err != nil {
return err
}
// Before:
defer func() {
err = errors.Join(err, f.Close())
}()
// After:
defer errorsx.Close(f, &err)