-
Notifications
You must be signed in to change notification settings - Fork 1
/
errors.go
132 lines (111 loc) · 2.33 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
package errors
import (
"fmt"
"golang.org/x/xerrors"
)
var Nothing bool
func create(msg string) *appError {
var e appError
e.message = msg
e.frame = xerrors.Caller(2)
return &e
}
func New(msg string) AppError {
return create(msg)
}
func Errorf(format string, args ...interface{}) AppError {
return create(fmt.Sprintf(format, args...))
}
func Wrap(err error, msg ...string) AppError {
if err == nil {
return nil
}
var m string
if len(msg) != 0 {
m = msg[0]
}
e := create(m)
e.next = err
return e
}
func Wrapf(err error, format string, args ...interface{}) AppError {
e := create(fmt.Sprintf(format, args...))
e.next = err
return e
}
func As(err error, target interface{}) bool {
return xerrors.As(err, target)
}
func AsAppError(err error) *appError {
if err == nil {
return nil
}
var e *appError
if xerrors.As(err, &e) {
return e
}
return nil
}
type appError struct {
// 標準のエラー仕様を満たす変数
next error
message string
frame xerrors.Frame
// 独自の拡張仕様の変数
data []map[string]interface{}
level level
// APIエラー
code string
infoMessage string
status int
}
func (e *appError) Error() string {
// 一番下位層のメッセージを取り出す
next := AsAppError(e.next)
if next != nil {
return next.Error()
}
if e.next == nil {
if e.message != `` {
return e.message
}
return `no message`
}
return e.next.Error()
}
func (e *appError) Is(err error) bool {
if er := AsAppError(err); er != nil {
return e.Code() == er.Code()
}
return false
}
func (e *appError) Unwrap() error { return e.next }
func (e *appError) Format(s fmt.State, v rune) { xerrors.FormatError(e, s, v) }
func (e *appError) FormatError(p xerrors.Printer) error {
var message string
if e.level != "" {
message += fmt.Sprintf("[%s] ", e.level)
}
if e.code != "" {
message += fmt.Sprintf("[%s] ", e.code)
}
if e.message != "" {
message += fmt.Sprintf("%s", e.message)
}
if len(e.data) != 0 {
if message != "" {
message += "\n"
}
message += fmt.Sprintf("data: %+v", e.data)
}
p.Print(message)
e.frame.Format(p)
return e.next
}
func (e *appError) AddData(field string, data interface{}) AppError {
if e.data == nil {
e.data = make([]map[string]interface{}, 0)
}
e.data = append(e.data, map[string]interface{}{field: data})
return e
}