Skip to content

🧨 Extensions for the standard errors package

License

Notifications You must be signed in to change notification settings

go-simpler/errorsx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

errorsx

checks pkg.go.dev goreportcard codecov

Extensions for the standard errors package.

📦 Install

Go 1.21+

go get go-simpler.org/errorsx

📋 Usage

IsAny

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)
}

As

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)
}

Close

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)