-
Notifications
You must be signed in to change notification settings - Fork 0
/
werror.go
80 lines (65 loc) · 1.17 KB
/
werror.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
package werror
import (
"errors"
"strings"
)
func Wrap(err error, cause error) error {
flag := byte(0)
if err != nil {
flag |= 0x01
}
if cause != nil {
flag |= 0x02
}
switch flag {
case 0x01:
return err
case 0x02:
return cause
case 0x03:
return &ErrorNode{
error: err,
cause: cause,
}
}
return nil
}
func Cause(err error) error {
if c, ok := err.(interface{ Cause() error }); ok {
return c.Cause()
}
return nil
}
type ErrorNode struct {
error error // current
cause error // next
}
func (e *ErrorNode) Error() string {
var b strings.Builder
e.walk(&b)
return b.String()
}
func (e *ErrorNode) walk(b *strings.Builder) {
walkNode(b, e.error)
b.WriteRune('\n')
walkNode(b, e.cause)
}
func walkNode(b *strings.Builder, err error) {
if n, ok := err.(*ErrorNode); ok {
n.walk(b)
} else {
b.WriteString(err.Error())
}
}
func (e *ErrorNode) Unwrap() error {
return e.error
}
func (e *ErrorNode) Is(err error) bool {
return errors.Is(e.error, err) || errors.Is(e.cause, err)
}
func (e *ErrorNode) As(dst interface{}) bool {
return errors.As(e.error, dst) || errors.As(e.cause, dst)
}
func (e *ErrorNode) Cause() error {
return e.cause
}