1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package errors implements functions to manipulate errors.
7 // The New function creates errors whose only content is a text message.
9 // An error e wraps another error if e's type has one of the methods
14 // If e.Unwrap() returns a non-nil error w or a slice containing w,
15 // then we say that e wraps w. A nil error returned from e.Unwrap()
16 // indicates that e does not wrap any error. It is invalid for an
17 // Unwrap method to return an []error containing a nil error value.
19 // An easy way to create wrapped errors is to call fmt.Errorf and apply
20 // the %w verb to the error argument:
22 // wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
24 // Successive unwrapping of an error creates a tree. The Is and As
25 // functions inspect an error's tree by examining first the error
26 // itself followed by the tree of each of its children in turn
27 // (pre-order, depth-first traversal).
29 // Is examines the tree of its first argument looking for an error that
30 // matches the second. It reports whether it finds a match. It should be
31 // used in preference to simple equality checks:
33 // if errors.Is(err, fs.ErrExist)
37 // if err == fs.ErrExist
39 // because the former will succeed if err wraps fs.ErrExist.
41 // As examines the tree of its first argument looking for an error that can be
42 // assigned to its second argument, which must be a pointer. If it succeeds, it
43 // performs the assignment and returns true. Otherwise, it returns false. The form
45 // var perr *fs.PathError
46 // if errors.As(err, &perr) {
47 // fmt.Println(perr.Path)
52 // if perr, ok := err.(*fs.PathError); ok {
53 // fmt.Println(perr.Path)
56 // because the former will succeed if err wraps an *fs.PathError.
59 // New returns an error that formats as the given text.
60 // Each call to New returns a distinct error value even if the text is identical.
61 func New(text string) error {
62 return &errorString{text}
65 // errorString is a trivial implementation of error.
66 type errorString struct {
70 func (e *errorString) Error() string {
74 // ErrUnsupported indicates that a requested operation cannot be performed,
75 // because it is unsupported. For example, a call to os.Link when using a
76 // file system that does not support hard links.
78 // Functions and methods should not return this error but should instead
79 // return an error including appropriate context that satisfies
81 // errors.Is(err, errors.ErrUnsupported)
83 // either by directly wrapping ErrUnsupported or by implementing an Is method.
85 // Functions and methods should document the cases in which an error
86 // wrapping this will be returned.
87 var ErrUnsupported = New("unsupported operation")