-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
136 lines (114 loc) · 2.41 KB
/
errors.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Package errors is a drop-in replacement for Golang lib 'errors'.
package errors
import (
"strings"
"v2ray.com/core/common/serial"
)
// Severity describes how severe the error is.
type Severity int
const (
SeverityDebug Severity = iota
SeverityInfo
SeverityWarning
SeverityError
)
type hasInnerError interface {
// Inner returns the underlying error of this one.
Inner() error
}
type hasSeverity interface {
Severity() Severity
}
// Error is an error object with underlying error.
type Error struct {
message []interface{}
inner error
severity Severity
path []string
}
// Error implements error.Error().
func (v *Error) Error() string {
msg := serial.Concat(v.message...)
if v.inner != nil {
msg += " > " + v.inner.Error()
}
if len(v.path) > 0 {
msg = strings.Join(v.path, "|") + ": " + msg
}
return msg
}
// Inner implements hasInnerError.Inner()
func (v *Error) Inner() error {
if v.inner == nil {
return nil
}
return v.inner
}
func (v *Error) Base(err error) *Error {
v.inner = err
return v
}
func (v *Error) atSeverity(s Severity) *Error {
v.severity = s
return v
}
func (v *Error) Severity() Severity {
if v.inner == nil {
return v.severity
}
if s, ok := v.inner.(hasSeverity); ok {
as := s.Severity()
if as > v.severity {
return as
}
}
return v.severity
}
// AtDebug sets the severity to debug.
func (v *Error) AtDebug() *Error {
return v.atSeverity(SeverityDebug)
}
// AtInfo sets the severity to info.
func (v *Error) AtInfo() *Error {
return v.atSeverity(SeverityInfo)
}
// AtWarning sets the severity to warning.
func (v *Error) AtWarning() *Error {
return v.atSeverity(SeverityWarning)
}
// AtError sets the severity to error.
func (v *Error) AtError() *Error {
return v.atSeverity(SeverityError)
}
// Path sets the path to the location where this error happens.
func (v *Error) Path(path ...string) *Error {
v.path = path
return v
}
// New returns a new error object with message formed from given arguments.
func New(msg ...interface{}) *Error {
return &Error{
message: msg,
severity: SeverityInfo,
}
}
// Cause returns the root cause of this error.
func Cause(err error) error {
if err == nil {
return nil
}
for {
inner, ok := err.(hasInnerError)
if !ok || inner.Inner() == nil {
break
}
err = inner.Inner()
}
return err
}
func GetSeverity(err error) Severity {
if s, ok := err.(hasSeverity); ok {
return s.Severity()
}
return SeverityInfo
}