errorsx

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2025 License: MPL-2.0 Imports: 2 Imported by: 2

README ¶

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)

Documentation ¶

Overview ¶

Package errorsx implements extensions for the standard errors package.

Index ¶

Examples ¶

Constants ¶

This section is empty.

Variables ¶

This section is empty.

Functions ¶

func As ¶ added in v0.10.0

func As[T any](err error) (T, bool)

As is a generic version of errors.As.

Example ¶
package main

import (
	"fmt"
	"os"

	"go-simpler.org/errorsx"
)

var err error

func main() {
	if pathErr, ok := errorsx.As[*os.PathError](err); ok {
		fmt.Println(pathErr.Path)
	}
}
Output:

func Close ¶

func Close(c io.Closer, err *error)

Close attempts to close the given io.Closer and assigns the returned error (if any) to err. If err is already not nil, it will be joined with the io.Closer's error.

Example ¶
package main

import (
	"os"

	"go-simpler.org/errorsx"
)

func main() {
	_ = func() (err error) {
		f, err := os.Open("file.txt")
		if err != nil {
			return err
		}
		defer errorsx.Close(f, &err)

		return nil
	}
}
Output:

func IsAny ¶

func IsAny(err, target error, targets ...error) bool

IsAny is a multi-target version of errors.Is.

Example ¶
package main

import (
	"fmt"
	"os"

	"go-simpler.org/errorsx"
)

var err error

func main() {
	if errorsx.IsAny(err, os.ErrNotExist, os.ErrPermission) {
		fmt.Println(err)
	}
}
Output:

Types ¶

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL