forked from go-errors/errors
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreation_examples_test.go
More file actions
74 lines (64 loc) · 1.53 KB
/
creation_examples_test.go
File metadata and controls
74 lines (64 loc) · 1.53 KB
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
package errors
import (
"fmt"
"io"
)
func ExampleNew() {
// call some error returning function
err := func() error { return io.ErrUnexpectedEOF }()
// calling New attaches the current stacktrace to the existing UnexpectedEOF error
err = New(err)
// do something with the error
fmt.Println(err)
}
func ExampleWrap() {
// if recovered from panic
if err := recover(); err != nil {
// wrap the error, adding stacktrace, skipping one frame
err = Wrap(err, 1)
// do something with the error
fmt.Println(err)
}
// else, do something else
fmt.Println(a())
}
func ExampleErrorf() {
// example function
halve := func(x int) (int, error) {
// if number cannot be halved without remainedr
if x%2 != 0 {
return 0, Errorf("cannot halve %v without remainder", x)
}
// else, return halved number
return x / 2, nil
}
// call the function
val, err := halve(3)
// do something with the error
if err != nil {
fmt.Println("halve(3) failed", err)
} else {
fmt.Println("halve(3) worked:", val)
}
}
func ExampleWrapError() {
// example function that returns error
example := func() (int, error) {
// Wrap io.EOF with the current stack-trace and return it
return 0, Wrap(io.EOF, 0)
}
// call the function
_, err := example()
// do something with the error
fmt.Println(err)
}
func ExampleWrapError_skip() {
defer func() {
if err := recover(); err != nil {
// skip 1 frame (the deferred function) and then return the wrapped err
err = Wrap(err, 1)
// do something with the error
fmt.Println(err)
}
}()
}