-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
104 lines (88 loc) · 1.89 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
// Package errors is a drop-in replacement for Golang lib 'errors'.
package errors
import (
"fmt"
"v2ray.com/core/common/serial"
)
type hasInnerError interface {
// Inner returns the underlying error of this one.
Inner() error
}
type actionRequired interface {
ActionRequired() bool
}
// Error is an error object with underlying error.
type Error struct {
message string
inner error
actionRequired bool
}
// Error implements error.Error().
func (v Error) Error() string {
return v.message
}
// Inner implements hasInnerError.Inner()
func (v Error) Inner() error {
if v.inner == nil {
return nil
}
return v.inner
}
func (v Error) ActionRequired() bool {
return v.actionRequired
}
func (v Error) RequireUserAction() Error {
v.actionRequired = true
return v
}
func (v Error) Message(msg ...interface{}) Error {
return Error{
inner: v,
message: serial.Concat(msg...),
}
}
func (v Error) Format(format string, values ...interface{}) Error {
return v.Message(fmt.Sprintf(format, values...))
}
// New returns a new error object with message formed from given arguments.
func New(msg ...interface{}) Error {
return Error{
message: serial.Concat(msg...),
}
}
// Base returns an Error based on the given error.
func Base(err error) Error {
return Error{
inner: err,
}
}
func Format(format string, values ...interface{}) error {
return New(fmt.Sprintf(format, values...))
}
// 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 IsActionRequired(err error) bool {
for err != nil {
if ar, ok := err.(actionRequired); ok && ar.ActionRequired() {
return true
}
inner, ok := err.(hasInnerError)
if !ok || inner.Inner() == nil {
break
}
err = inner.Inner()
}
return false
}