exp: golang.org/x/exp/errors Index | Examples | Files | Directories

package errors

import "golang.org/x/exp/errors"

Package errors implements functions to manipulate errors.

This package implements the Go 2 draft designs for error inspection and printing:

https://go.googlesource.com/proposal/+/master/design/go2draft.md

This is an EXPERIMENTAL package, and may change in arbitrary ways without notice.

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

errors.go format.go

func New Uses

func New(text string) error

New returns an error that formats as the given text.

Code:

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:

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

type Formatter Uses

type Formatter interface {
    // Format prints the receiver's first error and returns the next error in
    // the error chain, if any.
    Format(p Printer) (next error)
}

A Formatter formats error messages.

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. Localization packages such as golang.org/x/text/message typically provide their own implementations.

Directories

PathSynopsis
fmtPackage fmt implements formatted I/O with functions analogous to C's printf and scanf.

Updated 2018-10-22. Refresh now. Tools for package owners.