-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
executable file
·67 lines (50 loc) · 1.21 KB
/
example_test.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
package goerrors
import (
"fmt"
"os"
)
func Example() {
// A function which open a file
openFile := func(name string) (*os.File, error) {
f, err := os.Open(name)
// Decorate the opening error
if err != nil {
return nil, DecorateError(err)
}
return f, nil
}
// A function which read one byte in the opened file
readFile := func(f *os.File) (byte, error) {
var b [1]byte
n, err := f.Read(b[:])
// Decorate the read error
if err != nil {
return 0, DecorateError(err)
}
// Return custom error
if n == 0 {
return 0, MakeError("No data to read")
}
return b[0], nil
}
// Deactivate stack trace
// (cause stacktrace produced for testing package is specific to go installation and may change with Go version)
SetDebug(false)
// Make an unfindable filename
const name = ".a_file_5123351069599224559.txt"
// Call the checked open function
f, err := openFile(name)
if err != nil {
fmt.Println(err)
return
}
// Here, in this example, this code won't never be executed if the file can't be opened
defer f.Close()
_, err = readFile(f)
if err != nil {
fmt.Println(err)
return
}
// Output:
// StandardError: open .a_file_5123351069599224559.txt: no such file or directory
}