errorsx

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2023 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 get go-simpler.org/errorsx

📋 Usage

IsAny

A multi-target version of errors.Is.

if errorsx.IsAny(err, os.ErrNotExist, os.ErrPermission) {
    fmt.Println(err)
}
HasType

Reports whether the error has type T. It is equivalent to errors.As without the need to declare the target variable.

if errorsx.HasType[*os.PathError](err) {
    fmt.Println(err)
}
Split

Returns errors joined by errors.Join or by fmt.Errorf with multiple %w verbs. If the given error was created differently, Split returns nil.

if errs := errorsx.Split(err); errs != nil {
    fmt.Println(errs)
}
Close

Attempts to close the given io.Closer and assigns the returned error (if any) to err.

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

    return nil
}()

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 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 HasType ¶ added in v0.7.0

func HasType[T any](err error) bool

HasType reports whether the error has type T. It is equivalent to errors.As without the need to declare the target variable.

Example ¶
package main

import (
	"fmt"
	"os"

	"go-simpler.org/errorsx"
)

var err error

func main() {
	if errorsx.HasType[*os.PathError](err) {
		fmt.Println(err)
	}
}
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:

func Split ¶ added in v0.8.0

func Split(err error) []error

Split returns errors joined by errors.Join or by fmt.Errorf with multiple %w verbs. If the given error was created differently, Split returns nil.

Example ¶
package main

import (
	"fmt"

	"go-simpler.org/errorsx"
)

var err error

func main() {
	if errs := errorsx.Split(err); errs != nil {
		fmt.Println(errs)
	}
}
Output:

Types ¶

This section is empty.

Jump to

Keyboard shortcuts

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