Go: errors Index | Examples | Files

package errors

import "errors"

Package errors implements functions to manipulate errors.

The New function creates errors whose only content is a text message.

The Unwrap, Is and As functions work on errors that may wrap other errors. An error wraps another error if its type has the method

Unwrap() error

If e.Unwrap() returns a non-nil error w, then we say that e wraps w.

A simple way to create wrapped errors is to call fmt.Errorf and apply the %w verb to the error argument:

fmt.Errorf("... %w ...", ..., err, ...).Unwrap()

returns err.

Unwrap unpacks wrapped errors. If its argument's type has an Unwrap method, it calls the method once. Otherwise, it returns nil.

Is unwraps its first argument sequentially looking for an error that matches the second. It reports whether it finds a match. It should be used in preference to simple equality checks:

if errors.Is(err, os.ErrExist)

is preferable to

if err == os.ErrExist

because the former will succeed if err wraps os.ErrExist.

As unwraps its first argument sequentially looking for an error that can be assigned to its second argument, which must be a pointer. If it succeeds, it performs the assignment and returns true. Otherwise, it returns false. The form

var perr *os.PathError
if errors.As(err, &perr) {
	fmt.Println(perr.Path)
}

is preferable to

if perr, ok := err.(*os.PathError); ok {
	fmt.Println(perr.Path)
}

because the former will succeed if err wraps an *os.PathError.

Code:play 

package main

import (
    "fmt"
    "time"
)

// MyError is an error implementation that includes a time and message.
type MyError struct {
    When time.Time
    What string
}

func (e MyError) Error() string {
    return fmt.Sprintf("%v: %v", e.When, e.What)
}

func oops() error {
    return MyError{
        time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
        "the file system has gone away",
    }
}

func main() {
    if err := oops(); err != nil {
        fmt.Println(err)
    }
}

Index

Examples

Package Files

errors.go wrap.go

func As Uses

func As(err error, target interface{}) bool

As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

Code:play 

if _, err := os.Open("non-existing"); err != nil {
    var pathError *os.PathError
    if errors.As(err, &pathError) {
        fmt.Println("Failed at path:", pathError.Path)
    } else {
        fmt.Println(err)
    }
}

Output:

Failed at path: non-existing

func Is Uses

func Is(err, target error) bool

Is reports whether any error in err's chain matches target.

The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

func New Uses

func New(text string) error

New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

Code:play 

err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
    fmt.Print(err)
}

Output:

emit macho dwarf: elf header corrupted

The fmt package's Errorf function lets us use the package's formatting features to create descriptive error messages.

Code:play 

const name, id = "bimmler", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
if err != nil {
    fmt.Print(err)
}

Output:

user "bimmler" (id 17) not found

func Unwrap Uses

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

Package errors imports 1 packages (graph) and is imported by 219408 packages. Updated 2019-09-19. Refresh now. Tools for package owners.