-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy patherrbox.go
112 lines (102 loc) · 1.6 KB
/
errbox.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
package gust
import (
"errors"
"fmt"
)
var _ error = (*ErrBox)(nil)
// ToErrBox wraps any error type.
func ToErrBox(val any) *ErrBox {
if eb, ok := val.(*ErrBox); ok {
return eb
}
return &ErrBox{val: val}
}
func toError(e any) error {
if x, is := e.(error); is {
return x
}
return ToErrBox(e)
}
// ErrBox is a wrapper for any error type.
type ErrBox struct {
val any
}
// Value returns the inner value.
func (a *ErrBox) Value() any {
if a == nil {
return nil
}
return a.val
}
// Error returns the string representation.
func (a *ErrBox) Error() string {
if a == nil {
return ""
}
switch val := a.val.(type) {
case string:
return val
case error:
return val.Error()
case nil:
return ""
default:
return fmt.Sprintf("%v", val)
}
}
// Unwrap returns the inner error.
func (a *ErrBox) Unwrap() error {
if a == nil {
return nil
}
switch val := a.val.(type) {
case nil:
return nil
case error:
u, ok := val.(interface {
Unwrap() error
})
if ok {
return u.Unwrap()
}
return val
default:
return nil
}
}
func (a *ErrBox) Is(target error) bool {
switch t := target.(type) {
case *ErrBox:
if t == nil {
return a == nil
}
if a == nil {
return false
}
return a.val == t.val
default:
b := a.Unwrap()
if b != nil {
return errors.Is(b, target)
}
return false
}
}
func (a *ErrBox) As(target any) bool {
if target == nil {
panic("errors: target cannot be nil")
}
t, ok := target.(*ErrBox)
if ok {
if t != nil {
t.val = a.val
return true
}
return false
}
b := a.Unwrap()
if b != nil {
return errors.As(b, target)
}
return false
}