-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy patherror.go
134 lines (116 loc) · 2.48 KB
/
error.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
package gotsrpc
import (
"fmt"
"io"
"reflect"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
type Error struct {
Msg string `json:"m"`
Pkg string `json:"p"`
Type string `json:"t"`
Data interface{} `json:"d,omitempty"`
ErrCause *Error `json:"c,omitempty"`
}
// NewError returns a new instance
func NewError(err error) *Error {
// check if already transformed
if v, ok := err.(*Error); ok { //nolint:errorlint
return v
}
// skip *withStack error type
if _, ok := err.(interface {
StackTrace() errors.StackTrace
}); ok && errors.Unwrap(err) != nil {
err = errors.Unwrap(err)
}
// retrieve error details
errType := reflect.TypeOf(err)
errElem := errType
if errType.Kind() == reflect.Ptr {
errElem = errType.Elem()
}
inst := &Error{
Msg: err.Error(),
Type: errType.String(),
Pkg: errElem.PkgPath(),
Data: err,
}
// unwrap error
if unwrappedErr := errors.Unwrap(err); unwrappedErr != nil {
inst.ErrCause = NewError(unwrappedErr)
inst.Msg = strings.TrimSuffix(inst.Msg, ": "+unwrappedErr.Error())
}
return inst
}
// As interface
func (e *Error) As(err interface{}) bool {
if e == nil || err == nil {
return false
}
if reflect.TypeOf(err).Elem().String() == e.Type {
if decodeErr := mapstructure.Decode(e.Data, &err); decodeErr != nil {
fmt.Printf("ERROR: failed to decode error data\n%+v", decodeErr)
return false
} else {
return true
}
}
return false
}
// Cause interface
func (e *Error) Cause() error {
if e.ErrCause != nil {
return e.ErrCause
}
return e
}
// Format interface
func (e *Error) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
_, _ = fmt.Fprintf(s, "%s.(%s)\n", e.Pkg, e.Type)
if e.Data != nil {
_, _ = fmt.Fprintf(s, "Data: %v\n", e.Data)
}
}
fallthrough
case 's', 'q':
_, _ = io.WriteString(s, e.Error())
}
}
// Unwrap interface
func (e *Error) Unwrap() error {
if e != nil && e.ErrCause != nil {
return e.ErrCause
}
return nil
}
// Is interface
func (e *Error) Is(err error) bool {
if e == nil || err == nil {
return false
}
errType := reflect.TypeOf(err)
errElem := errType
if errType.Kind() == reflect.Ptr {
errElem = errType.Elem()
}
if e.Msg == err.Error() &&
errType.String() == e.Type &&
errElem.PkgPath() == e.Pkg {
return true
}
return false
}
// Error interface
func (e *Error) Error() string {
msg := e.Msg
if e.ErrCause != nil {
msg += ": " + e.ErrCause.Error()
}
return msg
}