-
Notifications
You must be signed in to change notification settings - Fork 9
/
examples.go
74 lines (61 loc) · 1.3 KB
/
examples.go
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
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// This file contains code patterns where `try` might
// be effective.
// TODO(gri) expand and use as actual tests for `try`.
package p
func f() error {
return nil
}
type myError struct {
error
}
func sharedReturnExpr() error {
if err := f(); err != nil {
return myError{err}
}
if err := f(); err != nil {
return myError{err}
}
}
func notSharedReturnExpr() error {
if err := f(); err != nil {
return myError{err}
}
if err := f(); err != nil {
return myError{err}
}
if err := f(); err != nil {
return err
}
}
// f uses a function literal to annotate errors uniformly
func f(arg int) error {
report := func(err error) error { return fmt.Errorf("f failed for %v: %v", arg, err) }
err := g(arg)
if err != nil {
return report(err)
}
err = h(arg)
if err != nil {
return report(err)
}
return nil
}
// g uses repeated code (e.g., copy/paste) to annotate errors uniformly
func g(arg int) error {
err := h(arg)
if err != nil {
return fmt.Errorf("g failed for %v: %v", arg, err)
}
err = f(arg)
if err != nil {
return fmt.Errorf("g failed for %v: %v", arg, err)
}
return nil
}
func h(arg int) error {
return nil
}