xerrors: golang.org/x/xerrors Index | Examples | Files | Directories

package xerrors

import "golang.org/x/xerrors"

Package xerrors implements functions to manipulate errors.

This package supports transitioning to the Go 2 proposal for error values:

https://golang.org/design/29934-error-values

Most of the functions and types in this package will be incorporated into the standard library's errors package in Go 1.13; the behavior of this package's Errorf function will be incorporated into the standard library's fmt.Errorf. Use this package to get equivalent behavior in all supported Go versions. For example, create errors using

xerrors.New("write failed")

or

xerrors.Errorf("while reading: %v", err)

If you want your error type to participate in the new formatting implementation for %v and %+v, provide it with a Format method that calls xerrors.FormatError, as shown in the example for FormatError.

Code:

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

adaptor_go1_12.go doc.go errors.go fmt.go format_go1_12.go frame_go1_12.go wrap.go

func As Uses

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

As finds the first error in err's chain that matches the type to which target points, and if so, sets the target to its value and returns true. An error matches a type if it is assignable to the target type, or if it has a method As(interface{}) bool such that As(target) returns true. As will panic if target is not a non-nil pointer to a type which implements error or is of interface type.

The As method should set the target to its value and return true if err matches the type to which target points.

Code:

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

Output:

Failed at path: non-existing

func Errorf Uses

func Errorf(format string, a ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error.

The returned error includes the file and line number of the caller when formatted with additional detail enabled. If the last argument is an error the returned error's Format method will return it if the format string ends with ": %s", ": %v", or ": %w". If the last argument is an error and the format string ends with ": %w", the returned error implements Wrapper with an Unwrap method returning it.

func FormatError Uses

func FormatError(f Formatter, s fmt.State, verb rune)

FormatError calls the FormatError method of f with an errors.Printer configured according to s and verb, and writes the result to s.

Code:

package main

import (
    "fmt"

    "golang.org/x/xerrors"
)

type MyError2 struct {
    Message string
    frame   xerrors.Frame
}

func (m *MyError2) Error() string {
    return m.Message
}

func (m *MyError2) Format(f fmt.State, c rune) { // implements fmt.Formatter
    xerrors.FormatError(m, f, c)
}

func (m *MyError2) FormatError(p xerrors.Printer) error { // implements xerrors.Formatter
    p.Print(m.Message)
    if p.Detail() {
        m.frame.Format(p)
    }
    return nil
}

func main() {
    err := &MyError2{Message: "oops", frame: xerrors.Caller(1)}
    fmt.Printf("%v\n", err)
    fmt.Println()
    fmt.Printf("%+v\n", err)
}

func Is Uses

func Is(err, target error) bool

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

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.

The returned error contains a Frame set to the caller's location and implements Formatter to show this information when printed with details.

Code:

err := xerrors.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:

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 Opaque Uses

func Opaque(err error) error

Opaque returns an error with the same error formatting as err but that does not match err and cannot be unwrapped.

func Unwrap Uses

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err implements Unwrap. Otherwise, Unwrap returns nil.

type Formatter Uses

type Formatter interface {
    error

    // FormatError prints the receiver's first error and returns the next error in
    // the error chain, if any.
    FormatError(p Printer) (next error)
}

A Formatter formats error messages.

type Frame Uses

type Frame struct {
    // contains filtered or unexported fields
}

A Frame contains part of a call stack.

func Caller Uses

func Caller(skip int) Frame

Caller returns a Frame that describes a frame on the caller's stack. The argument skip is the number of frames to skip over. Caller(0) returns the frame for the caller of Caller.

func (Frame) Format Uses

func (f Frame) Format(p Printer)

Format prints the stack as error detail. It should be called from an error's Format implementation after printing any other error detail.

type Printer Uses

type Printer interface {
    // Print appends args to the message output.
    Print(args ...interface{})

    // Printf writes a formatted string.
    Printf(format string, args ...interface{})

    // Detail reports whether error detail is requested.
    // After the first call to Detail, all text written to the Printer
    // is formatted as additional detail, or ignored when
    // detail has not been requested.
    // If Detail returns false, the caller can avoid printing the detail at all.
    Detail() bool
}

A Printer formats error messages.

The most common implementation of Printer is the one provided by package fmt during Printf (as of Go 1.13). Localization packages such as golang.org/x/text/message typically provide their own implementations.

type Wrapper Uses

type Wrapper interface {
    // Unwrap returns the next error in the error chain.
    // If there is no next error, Unwrap returns nil.
    Unwrap() error
}

A Wrapper provides context around another error.

Directories

PathSynopsis
internal

Package xerrors imports 8 packages (graph) and is imported by 85 packages. Updated 2019-04-19. Refresh now. Tools for package owners.