Movatterモバイル変換


[0]ホーム

URL:


errors

packagestandard library
go1.26.0Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License:BSD-3-ClauseImports:2Imported by:1,580,116

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package errors implements functions to manipulate errors.

TheNew function creates errors whose only content is a text message.

An error e wraps another error if e's type has one of the methods

Unwrap() errorUnwrap() []error

If e.Unwrap() returns a non-nil error w or a slice containing w,then we say that e wraps w. A nil error returned from e.Unwrap()indicates that e does not wrap any error. It is invalid for anUnwrap method to return an []error containing a nil error value.

An easy way to create wrapped errors is to callfmt.Errorf and applythe %w verb to the error argument:

wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)

Successive unwrapping of an error creates a tree. TheIs andAsfunctions inspect an error's tree by examining first the erroritself followed by the tree of each of its children in turn(pre-order, depth-first traversal).

Seehttps://go.dev/blog/go1.13-errors for a deeper discussion of thephilosophy of wrapping and when to wrap.

Is examines the tree of its first argument looking for an error thatmatches the second. It reports whether it finds a match. It should beused in preference to simple equality checks:

if errors.Is(err, fs.ErrExist)

is preferable to

if err == fs.ErrExist

because the former will succeed if err wrapsio/fs.ErrExist.

AsType examines the tree of its argument looking for an error whosetype matches its type argument. If it succeeds, it returns thecorresponding value of that type and true. Otherwise, it returns thezero value of that type and false. The form

if perr, ok := errors.AsType[*fs.PathError](err); ok {fmt.Println(perr.Path)}

is preferable to

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

because the former will succeed if err wraps an*io/fs.PathError.

Example
package mainimport ("fmt""time")// MyError is an error implementation that includes a time and message.type MyError struct {When time.TimeWhat 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)}}
Output:1989-03-15 22:30:00 +0000 UTC: the file system has gone away

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUnsupported =New("unsupported operation")

ErrUnsupported indicates that a requested operation cannot be performed,because it is unsupported. For example, a call toos.Link when using afile system that does not support hard links.

Functions and methods should not return this error but should insteadreturn an error including appropriate context that satisfies

errors.Is(err, errors.ErrUnsupported)

either by directly wrapping ErrUnsupported or by implementing anIs method.

Functions and methods should document the cases in which an errorwrapping this will be returned.

Functions

funcAsadded ingo1.13

func As(errerror, targetany)bool

As finds the first error in err's tree that matches target, and if one is found, setstarget to that error value and returns true. Otherwise, it returns false.

For most uses, preferAsType. As is equivalent toAsType but sets its targetargument rather than returning the matching error and doesn't require its targetargument to implement error.

The tree consists of err itself, followed by the errors obtained by repeatedlycalling its Unwrap() error or Unwrap() []error method. When err wraps multipleerrors, As examines err followed by a depth-first traversal of its children.

An error matches target if the error's concrete value is assignable to the valuepointed to by target, or if the error has a method As(any) bool such thatAs(target) returns true. In the latter case, the As method is responsible forsetting target.

An error type might provide an As method so it can be treated as if it were adifferent error type.

As panics if target is not a non-nil pointer to either a type that implementserror, or to any interface type.

Example
package mainimport ("errors""fmt""io/fs""os")func main() {if _, err := os.Open("non-existing"); err != nil {var pathError *fs.PathErrorif errors.As(err, &pathError) {fmt.Println("Failed at path:", pathError.Path)} else {fmt.Println(err)}}}
Output:Failed at path: non-existing

Example (Custom_match)

Custom errors can implement a method "As(any) bool" to match against other error types,overriding the default matching oferrors.As.

package mainimport ("errors""fmt""io/fs")type MyAsError struct {err string}func (e MyAsError) Error() string {return e.err}func (e MyAsError) As(target any) bool {pe, ok := target.(**fs.PathError)if !ok {return false}*pe = &fs.PathError{Op:   "custom",Path: "/",Err:  errors.New(e.err),}return true}func main() {var err error = MyAsError{"an error"}fmt.Println("Error:", err)fmt.Printf("TypeOf err: %T\n", err)var pathError *fs.PathErrorok := errors.As(err, &pathError)fmt.Println("Error as fs.PathError:", ok)fmt.Println("fs.PathError:", pathError)}
Output:Error: an errorTypeOf err: errors_test.MyAsErrorError as fs.PathError: truefs.PathError: custom /: an error

funcAsTypeadded ingo1.26.0

func AsType[Eerror](errerror) (E,bool)

AsType finds the first error in err's tree that matches the type E, andif one is found, returns that error value and true. Otherwise, itreturns the zero value of E and false.

The tree consists of err itself, followed by the errors obtained byrepeatedly calling its Unwrap() error or Unwrap() []error method. Whenerr wraps multiple errors, AsType examines err followed by adepth-first traversal of its children.

An error err matches the type E if the type assertion err.(E) holds,or if the error has a method As(any) bool such that err.As(target)returns true when target is a non-nil *E. In the latter case, the Asmethod is responsible for setting target.

Example
package mainimport ("errors""fmt""io/fs""os")func main() {if _, err := os.Open("non-existing"); err != nil {if pathError, ok := errors.AsType[*fs.PathError](err); ok {fmt.Println("Failed at path:", pathError.Path)} else {fmt.Println(err)}}}
Output:Failed at path: non-existing

Example (Custom_match)

Custom errors can implement a method "As(any) bool" to match against other error types,overriding the default matching oferrors.AsType.

package mainimport ("errors""fmt""io/fs")type MyAsError struct {err string}func (e MyAsError) Error() string {return e.err}func (e MyAsError) As(target any) bool {pe, ok := target.(**fs.PathError)if !ok {return false}*pe = &fs.PathError{Op:   "custom",Path: "/",Err:  errors.New(e.err),}return true}func main() {var err error = MyAsError{"an error"}fmt.Println("Error:", err)fmt.Printf("TypeOf err: %T\n", err)pathError, ok := errors.AsType[*fs.PathError](err)fmt.Println("Error as fs.PathError:", ok)fmt.Println("fs.PathError:", pathError)}
Output:Error: an errorTypeOf err: errors_test.MyAsErrorError as fs.PathError: truefs.PathError: custom /: an error

funcIsadded ingo1.13

func Is(err, targeterror)bool

Is reports whether any error in err's tree matches target.The target must be comparable.

The tree consists of err itself, followed by the errors obtained by repeatedlycalling its Unwrap() error or Unwrap() []error method. When err wraps multipleerrors, Is examines err followed by a depth-first traversal of its children.

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

An error type might provide an Is method so it can be treated as equivalentto an existing error. For example, if MyError defines

func (m MyError) Is(target error) bool { return target == fs.ErrExist }

then Is(MyError{}, fs.ErrExist) returns true. Seesyscall.Errno.Is foran example in the standard library. An Is method should only shallowlycompare err and the target and not callUnwrap on either.

Example
package mainimport ("errors""fmt""io/fs""os")func main() {if _, err := os.Open("non-existing"); err != nil {if errors.Is(err, fs.ErrNotExist) {fmt.Println("file does not exist")} else {fmt.Println(err)}}}
Output:file does not exist

Example (Custom_match)

Custom errors can implement a method "Is(error) bool" to match other error values,overriding the default matching oferrors.Is.

package mainimport ("errors""fmt""io/fs")type MyIsError struct {err string}func (e MyIsError) Error() string {return e.err}func (e MyIsError) Is(err error) bool {return err == fs.ErrPermission}func main() {var err error = MyIsError{"an error"}fmt.Println("Error equals fs.ErrPermission:", err == fs.ErrPermission)fmt.Println("Error is fs.ErrPermission:", errors.Is(err, fs.ErrPermission))}
Output:Error equals fs.ErrPermission: falseError is fs.ErrPermission: true

funcJoinadded ingo1.20

func Join(errs ...error)error

Join returns an error that wraps the given errors.Any nil error values are discarded.Join returns nil if every value in errs is nil.The error formats as the concatenation of the strings obtainedby calling the Error method of each element of errs, with a newlinebetween each string.

A non-nil error returned by Join implements the Unwrap() []error method.The errors may be inspected withIs andAs.

Example
package mainimport ("errors""fmt")func main() {err1 := errors.New("err1")err2 := errors.New("err2")err := errors.Join(err1, err2)fmt.Println(err)if errors.Is(err, err1) {fmt.Println("err is err1")}if errors.Is(err, err2) {fmt.Println("err is err2")}fmt.Println(err.(interface{ Unwrap() []error }).Unwrap())}
Output:err1err2err is err1err is err2[err1 err2]

funcNew

func New(textstring)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.

Example
package mainimport ("errors""fmt")func main() {err := errors.New("emit macho dwarf: elf header corrupted")if err != nil {fmt.Print(err)}}
Output:emit macho dwarf: elf header corrupted

Example (Errorf)

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

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

Example (Unique)

Each call toerrors.New returns an unique instance of the error,even if the arguments are the same. To match against errorscreated byerrors.New, declare a sentinel error and reuse it.

package mainimport ("errors""fmt")func OopsNew() error {return errors.New("an error")}var ErrSentinel = errors.New("an error")func OopsSentinel() error {return ErrSentinel}func main() {err1 := OopsNew()err2 := OopsNew()fmt.Println("Errors using distinct errors.New calls:")fmt.Printf("Is(%q, %q) = %v\n", err1, err2, errors.Is(err1, err2))err3 := OopsSentinel()err4 := OopsSentinel()fmt.Println()fmt.Println("Errors using a sentinel error:")fmt.Printf("Is(%q, %q) = %v\n", err3, err4, errors.Is(err3, err4))}
Output:Errors using distinct errors.New calls:Is("an error", "an error") = falseErrors using a sentinel error:Is("an error", "an error") = true

funcUnwrapadded ingo1.13

func Unwrap(errerror)error

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

Unwrap only calls a method of the form "Unwrap() error".In particular Unwrap does not unwrap errors returned byJoin.

Example
package mainimport ("errors""fmt")func main() {err1 := errors.New("error1")err2 := fmt.Errorf("error2: [%w]", err1)fmt.Println(err2)fmt.Println(errors.Unwrap(err2))}
Output:error2: [error1]error1

Types

This section is empty.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2026 Movatter.jp