Skip to content

Commit 879543f

Browse files
committed
have sample of Try-prefix to use non-local error handling
1 parent bfa072b commit 879543f

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

samples/main-play.go

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,9 @@ func ClassicCopyFile(src, dst string) error {
6464
return nil
6565
}
6666

67-
// OrgCopyFile copies the source file to the given destination. If any error occurs it
67+
// TryCopyFile copies the source file to the given destination. If any error occurs it
6868
// returns an error value describing the reason.
69-
func OrgCopyFile(src, dst string) (err error) {
70-
defer err2.Handle(&err) // automatic error message: see err2.Formatter
69+
func TryCopyFile(src, dst string) {
7170
// You can out-comment above handler line(s) to see what happens.
7271

7372
// You'll learn that call stacks are for every function level 'catch'
@@ -79,17 +78,13 @@ func OrgCopyFile(src, dst string) (err error) {
7978
r := try.To1(os.Open(src))
8079
defer r.Close()
8180

82-
w, err := os.Create(dst)
83-
if err != nil {
84-
return fmt.Errorf("mixing traditional error checking: %w", err)
85-
}
81+
w:= try.To1(os.Create(dst))
8682
defer err2.Handle(&err, func(err error) error {
8783
try.Out(os.Remove(dst)).Logf("cleaning error")
8884
return err
8985
})
9086
defer w.Close()
9187
try.To1(io.Copy(w, r))
92-
return nil
9388
}
9489

9590
func CallRecur(d int) (ret int, err error) {
@@ -161,13 +156,13 @@ func doMain() (err error) {
161156
// how err2 works. Especially interesting is automatic stack tracing.
162157
//
163158
// source file exists, but the destination is not in high probability
164-
//try.To(OrgCopyFile("main.go", "/notfound/path/file.bak"))
159+
//TryCopyFile("main.go", "/notfound/path/file.bak")
165160

166161
// Both source and destination don't exist
167-
//try.To(OrgCopyFile("/notfound/path/file.go", "/notfound/path/file.bak"))
162+
//TryCopyFile("/notfound/path/file.go", "/notfound/path/file.bak")
168163

169164
// to play with real args:
170-
try.To(CopyFile(flag.Arg(0), flag.Arg(1)))
165+
TryCopyFile(flag.Arg(0), flag.Arg(1))
171166

172167
if len(flag.Args()) > 0 {
173168
// Next fn demonstrates how error and panic traces work, comment out all
@@ -177,7 +172,7 @@ func doMain() (err error) {
177172
fmt.Println("ret val:", ret)
178173
} else {
179174
// 2nd argument is empty to assert
180-
try.To(OrgCopyFile("main.go", ""))
175+
TryCopyFile("main.go", "")
181176
}
182177

183178
fmt.Println("=== you cannot see this ===")

0 commit comments

Comments
 (0)