-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmisc.go
110 lines (90 loc) · 2.09 KB
/
misc.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
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
package villa
import (
"fmt"
)
// N is a very long slice of elements with size of zero-bytes.
// It is useful for generating a serial of numbers in a for-range clause. e.g.
// for i := range villa.N[:200] { ... }
// The above i in the above for clause will range from 0 to 200(exclusive).
var N [int(^uint32(0) >> 1)]struct{}
// An variable of zero-size bytes
type Empty struct{}
// A channel for signaling stop
type Stop chan Empty
// Signal to stop
func (stop Stop) Stop() {
stop <- Empty{}
}
// Create a Stop with buffer size 1
func NewStop() Stop {
return make(Stop, 1)
}
/*
NestedError is an error with current message and nested error.
Use NestErrorf to generate a NestedError. It returns a nil for a nil nested
error.
Use NestedError.Deepest() to fetch the cause error.
*/
type NestedError interface {
error
// Message returns the messsage of this error
Message() string
// Nested returns the nested error
Nested() error
/*
Deepest returns the deepest non-NestedError error, which is the
original cause error.
*/
Deepest() error
}
type nestedError struct {
message string
nested error
}
// Error implements error interface
func (err *nestedError) Error() string {
if err.nested == nil {
return err.message
}
return err.message + ": " + err.nested.Error()
}
func (err *nestedError) Message() string {
return err.message
}
func (err *nestedError) Nested() error {
return err.nested
}
func (err *nestedError) Deepest() error {
if err.nested == nil {
return nil
}
ne, ok := err.nested.(NestedError)
if !ok {
return err.nested
}
return ne.Deepest()
}
/*
DeepestNested returns the deepest nested error. If err is not *NestedError,
it is directly returned.
*/
func DeepestNested(err error) error {
ne, ok := err.(NestedError)
if ok {
err = ne.Deepest()
}
return err
}
/*
NestErrorf returns nil if err == nil, otherwise it returns a *NestedError
error with a formatted message
*/
func NestErrorf(err error, fmtstr string, args ...interface{}) NestedError {
if err == nil {
return nil
}
return &nestedError{
message: fmt.Sprintf(fmtstr, args...),
nested: err,
}
}