summaryrefslogtreecommitdiff
path: root/devdocs/go/errors%2Findex.html
blob: 3eb8f8a2816c36e7030390f5088c20f416ddb659 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<h1> Package errors  </h1>     <ul id="short-nav">
<li><code>import "errors"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package errors implements functions to manipulate errors. </p>
<p>The <a href="#New">New</a> function creates errors whose only content is a text message. </p>
<p>An error e wraps another error if e's type has one of the methods </p>
<pre data-language="go">Unwrap() error
Unwrap() []error
</pre> <p>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 an Unwrap method to return an []error containing a nil error value. </p>
<p>An easy way to create wrapped errors is to call <span>fmt.Errorf</span> and apply the %w verb to the error argument: </p>
<pre data-language="go">wrapsErr := fmt.Errorf("... %w ...", ..., err, ...)
</pre> <p>Successive unwrapping of an error creates a tree. The <a href="#Is">Is</a> and <a href="#As">As</a> functions inspect an error's tree by examining first the error itself followed by the tree of each of its children in turn (pre-order, depth-first traversal). </p>
<p><a href="#Is">Is</a> examines the tree of its first argument looking for an error that matches the second. It reports whether it finds a match. It should be used in preference to simple equality checks: </p>
<pre data-language="go">if errors.Is(err, fs.ErrExist)
</pre> <p>is preferable to </p>
<pre data-language="go">if err == fs.ErrExist
</pre> <p>because the former will succeed if err wraps <span>io/fs.ErrExist</span>. </p>
<p><a href="#As">As</a> examines the tree of its first argument looking for an error that can be assigned to its second argument, which must be a pointer. If it succeeds, it performs the assignment and returns true. Otherwise, it returns false. The form </p>
<pre data-language="go">var perr *fs.PathError
if errors.As(err, &amp;perr) {
	fmt.Println(perr.Path)
}
</pre> <p>is preferable to </p>
<pre data-language="go">if perr, ok := err.(*fs.PathError); ok {
	fmt.Println(perr.Path)
}
</pre> <p>because the former will succeed if err wraps an <span>*io/fs.PathError</span>. </p>   <h4 id="example_"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">if err := oops(); err != nil {
    fmt.Println(err)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">1989-03-15 22:30:00 +0000 UTC: the file system has gone away
</pre>        <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#As">func As(err error, target any) bool</a></li>
<li><a href="#Is">func Is(err, target error) bool</a></li>
<li><a href="#Join">func Join(errs ...error) error</a></li>
<li><a href="#New">func New(text string) error</a></li>
<li><a href="#Unwrap">func Unwrap(err error) error</a></li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_">Package</a></dd> <dd><a class="exampleLink" href="#example_As">As</a></dd> <dd><a class="exampleLink" href="#example_Is">Is</a></dd> <dd><a class="exampleLink" href="#example_Join">Join</a></dd> <dd><a class="exampleLink" href="#example_New">New</a></dd> <dd><a class="exampleLink" href="#example_New_errorf">New (Errorf)</a></dd> <dd><a class="exampleLink" href="#example_Unwrap">Unwrap</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>errors.go</span> <span>join.go</span> <span>wrap.go</span>  </p>   <h2 id="pkg-variables">Variables</h2> <p>ErrUnsupported indicates that a requested operation cannot be performed, because it is unsupported. For example, a call to <span>os.Link</span> when using a file system that does not support hard links. </p>
<p>Functions and methods should not return this error but should instead return an error including appropriate context that satisfies </p>
<pre data-language="go">errors.Is(err, errors.ErrUnsupported)
</pre> <p>either by directly wrapping ErrUnsupported or by implementing an <a href="#Is">Is</a> method. </p>
<p>Functions and methods should document the cases in which an error wrapping this will be returned. </p>
<pre data-language="go">var ErrUnsupported = New("unsupported operation")</pre> <h2 id="As">func <span>As</span>  <span title="Added in Go 1.13">1.13</span> </h2> <pre data-language="go">func As(err error, target any) bool</pre> <p>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. </p>
<p>The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, As examines err followed by a depth-first traversal of its children. </p>
<p>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. </p>
<p>An error type might provide an As method so it can be treated as if it were a different error type. </p>
<p>As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type. </p>   <h4 id="example_As"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">if _, err := os.Open("non-existing"); err != nil {
    var pathError *fs.PathError
    if errors.As(err, &amp;pathError) {
        fmt.Println("Failed at path:", pathError.Path)
    } else {
        fmt.Println(err)
    }
}

</pre> <p>Output:</p> <pre class="output" data-language="go">Failed at path: non-existing
</pre>   <h2 id="Is">func <span>Is</span>  <span title="Added in Go 1.13">1.13</span> </h2> <pre data-language="go">func Is(err, target error) bool</pre> <p>Is reports whether any error in err's tree matches target. </p>
<p>The tree consists of err itself, followed by the errors obtained by repeatedly calling its Unwrap() error or Unwrap() []error method. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children. </p>
<p>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. </p>
<p>An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines </p>
<pre data-language="go">func (m MyError) Is(target error) bool { return target == fs.ErrExist }
</pre> <p>then Is(MyError{}, fs.ErrExist) returns true. See <span>syscall.Errno.Is</span> for an example in the standard library. An Is method should only shallowly compare err and the target and not call <a href="#Unwrap">Unwrap</a> on either. </p>   <h4 id="example_Is"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">if _, err := os.Open("non-existing"); err != nil {
    if errors.Is(err, fs.ErrNotExist) {
        fmt.Println("file does not exist")
    } else {
        fmt.Println(err)
    }
}

</pre> <p>Output:</p> <pre class="output" data-language="go">file does not exist
</pre>   <h2 id="Join">func <span>Join</span>  <span title="Added in Go 1.20">1.20</span> </h2> <pre data-language="go">func Join(errs ...error) error</pre> <p>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 obtained by calling the Error method of each element of errs, with a newline between each string. </p>
<p>A non-nil error returned by Join implements the Unwrap() []error method. </p>   <h4 id="example_Join"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">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")
}
</pre> <p>Output:</p> <pre class="output" data-language="go">err1
err2
err is err1
err is err2
</pre>   <h2 id="New">func <span>New</span>  </h2> <pre data-language="go">func New(text string) error</pre> <p>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. </p>   <h4 id="example_New"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
    fmt.Print(err)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">emit macho dwarf: elf header corrupted
</pre>      <h4 id="example_New_errorf"> <span class="text">Example (Errorf)</span>
</h4> <p>The fmt package's Errorf function lets us use the package's formatting features to create descriptive error messages. </p> <p>Code:</p> <pre class="code" data-language="go">const name, id = "bimmler", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
if err != nil {
    fmt.Print(err)
}
</pre> <p>Output:</p> <pre class="output" data-language="go">user "bimmler" (id 17) not found
</pre>   <h2 id="Unwrap">func <span>Unwrap</span>  <span title="Added in Go 1.13">1.13</span> </h2> <pre data-language="go">func Unwrap(err error) error</pre> <p>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. </p>
<p>Unwrap only calls a method of the form "Unwrap() error". In particular Unwrap does not unwrap errors returned by <a href="#Join">Join</a>. </p>   <h4 id="example_Unwrap"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">err1 := errors.New("error1")
err2 := fmt.Errorf("error2: [%w]", err1)
fmt.Println(err2)
fmt.Println(errors.Unwrap(err2))
</pre> <p>Output:</p> <pre class="output" data-language="go">error2: [error1]
error1
</pre><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/errors/" class="_attribution-link">http://golang.org/pkg/errors/</a>
  </p>
</div>