xerrors
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
This repository holds the transition packages for the new Go 1.13 error values.See golang.org/design/29934-error-values.
Documentation¶
Overview¶
Package xerrors implements functions to manipulate errors.
This package is based on the Go 2 proposal for error values:
https://go.dev/design/29934-error-values
These functions were incorporated into the standard library's errors packagein Go 1.13:- Is- As- Unwrap
Also, Errorf's %w verb was incorporated into fmt.Errorf.
No other features of this package were included in Go 1.13, and at presentthere are no plans to include any of them.
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¶
- func As(err error, target any) booldeprecated
- func Errorf(format string, a ...any) error
- func FormatError(f Formatter, s fmt.State, verb rune)
- func Is(err, target error) booldeprecated
- func New(text string) error
- func Opaque(err error) error
- func Unwrap(err error) errordeprecated
- type Formatter
- type Frame
- type Printer
- type Wrapper
Examples¶
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcAsdeprecated
As finds the first error in err's tree that matches target, and if one is found,sets target to that error value and returns true. Otherwise, it returns false.
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.
Deprecated: As of Go 1.13, this function simply callserrors.As.
Example¶
package mainimport ("fmt""os""golang.org/x/xerrors")func main() {_, err := os.Open("non-existing")if err != nil {var pathError *os.PathErrorif xerrors.As(err, &pathError) {fmt.Println("Failed at path:", pathError.Path)}}}
Output:Failed at path: non-existing
funcErrorf¶
Errorf formats according to a format specifier and returns the string as avalue that satisfies error.
The returned error includes the file and line number of the caller whenformatted with additional detail enabled. If the last argument is an errorthe returned error's Format method will return it if the format string endswith ": %s", ": %v", or ": %w". If the last argument is an error and theformat string ends with ": %w", the returned error implements an Unwrapmethod returning it.
If the format specifier includes a %w verb with an error operand in aposition other than at the end, the returned error will still implement anUnwrap method returning the operand, but the error's Format method will notreturn the wrapped error.
It is invalid to include more than one %w verb or to supply it with anoperand that does not implement the error interface. The %w verb is otherwisea synonym for %v.
Note that as of Go 1.13, the fmt.Errorf function will do error formatting,but it will not capture a stack backtrace.
funcFormatError¶
FormatError calls the FormatError method of f with an errors.Printerconfigured according to s and verb, and writes the result to s.
Example¶
package mainimport ("fmt""golang.org/x/xerrors")type MyError2 struct {Message stringframe xerrors.Frame}func (m *MyError2) Error() string {return m.Message}func (m *MyError2) Format(f fmt.State, c rune) { // implements fmt.Formatterxerrors.FormatError(m, f, c)}func (m *MyError2) FormatError(p xerrors.Printer) error { // implements xerrors.Formatterp.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)}
funcIsdeprecated
Is reports whether any error in err's tree matches target.
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.
Deprecated: As of Go 1.13, this function simply callserrors.Is.
funcNew¶
New returns an error that formats as the given text.
The returned error contains a Frame set to the caller's location andimplements Formatter to show this information when printed with details.
Example¶
package mainimport ("fmt""golang.org/x/xerrors")func main() {err := xerrors.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
funcOpaque¶
Opaque returns an error with the same error formatting as errbut that does not match err and cannot be unwrapped.
funcUnwrapdeprecated
Unwrap returns the result of calling the Unwrap method on err, if err implementsUnwrap. Otherwise, Unwrap returns nil.
Unwrap only calls a method of the form "Unwrap() error".In particular Unwrap does not unwrap errors returned byerrors.Join.
Deprecated: As of Go 1.13, this function simply callserrors.Unwrap.
Types¶
typeFormatter¶
type Formatter interface {error// FormatError prints the receiver's first error and returns the next error in// the error chain, if any.FormatError(pPrinter) (nexterror)}
A Formatter formats error messages.
typeFrame¶
type Frame struct {// contains filtered or unexported fields}
A Frame contains part of a call stack.
typePrinter¶
type Printer interface {// Print appends args to the message output.Print(args ...any)// Printf writes a formatted string.Printf(formatstring, args ...any)// 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 fmtduring Printf (as of Go 1.13). Localization packages such as golang.org/x/text/messagetypically provide their own implementations.