...

パッケージ errors

import "errors"
概要
目次

概要 ▾

errors パッケージはエラーを操作する関数を提供します。

コード:

package errors_test

import (
    "fmt"
    "time"
)

// MyError は時間とメッセージを含んだエラーです
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 Example() {
    if err := oops(); err != nil {
        fmt.Println(err)
    }
    // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
}

func As

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.

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.

コード:

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)
    }
}

出力:

Failed at path: non-existing

func Is

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

func New(text string) error

New は,渡されたテキストを表示するエラーを返します。

コード:

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

出力:

emit macho dwarf: elf header corrupted

例 (Errorf)

The fmt パッケージの Errorf 関数を使うと,fmt パッケージのフォーマットを使って 詳細なエラーメッセージを作成することができます。

コード:

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

出力:

user "bimmler" (id 17) not found

func Unwrap

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.