-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
failure.go
339 lines (289 loc) · 7.75 KB
/
failure.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Package failure provides an error handling library for Go.
// It allows you to create, wrap, and handle errors with additional context and features.
package failure
import (
"errors"
"fmt"
"io"
"reflect"
"strings"
)
// NewFailure creates a new Failure from an underlying error and optional fields.
// It panics if both the underlying error and fields are empty.
func NewFailure(underlying error, fieldsSet ...[]Field) Failure {
fieldCount := 0
for _, fields := range fieldsSet {
fieldCount += len(fields)
}
if underlying == nil && fieldCount == 0 {
panic("failure: invalid Failure")
}
f := &failure{
underlying: underlying,
}
if fieldCount == 0 {
return f
}
f.order = make([]any, 0, fieldCount)
f.fields = make(map[any]any, fieldCount)
setter := asSetter(*f)
for _, fields := range fieldsSet {
for _, f := range fields {
f.SetErrorField(&setter)
}
}
st := failure(setter)
return &st
}
func newFailure(err error, code any, fields []Field) error {
var defaultFields []Field
if code == nil {
defaultFields = []Field{
Callers(2),
}
} else {
defaultFields = []Field{
WithCode(code),
Callers(2),
}
}
return NewFailure(err, defaultFields, fields)
}
// Failure represents a error with additional information.
// It cannot be implemented by external types, but can be embedded within custom structs
// to implement custom methods.
type Failure interface {
error
Value(key any) any
// methods below are explicitly defined to support embedding in custom structs.
fmt.Formatter
Unwrap() error
As(target any) bool
// Prevent from implementing Failure without embedding.
foreach(f func(k, v any))
}
var _ Failure = (*failure)(nil)
type failure struct {
underlying error
fields map[any]any
order []any
}
// asSetter implements FieldSetter interface for failure struct.
// failure struct does not implement FieldSetter interface directly to prevent
// setting fields from outside of the package.
type asSetter failure
func (f *asSetter) Set(key, value any) {
if _, exists := f.fields[key]; exists {
panic(fmt.Sprintf("failure: duplicate error field key: %T(%v)", key, key))
}
f.order = append(f.order, key)
f.fields[key] = value
}
func (f *failure) Unwrap() error {
if f.underlying == nil {
return nil
}
return f.underlying
}
func (f *failure) Error() string {
var b strings.Builder
fieldsCount := len(f.fields)
if v, ok := f.fields[KeyCallStack]; ok {
fieldsCount--
head := v.(CallStack).HeadFrame()
b.WriteString(head.Pkg())
b.WriteRune('.')
b.WriteString(head.Func())
}
if v, ok := f.fields[KeyCode]; ok {
fieldsCount--
b.WriteString("[")
fmt.Fprint(&b, v)
b.WriteRune(']')
}
if fieldsCount > 0 {
first := true
b.WriteRune('(')
f.foreach(func(k, v any) {
switch k {
case KeyCode, KeyCallStack:
return
case KeyContext, KeyMessage:
}
if !first {
b.WriteString(", ")
}
first = false
if ef, ok := v.(ErrorFormatter); ok {
ef.FormatError(&b)
} else {
fmt.Fprint(&b, v)
}
})
b.WriteRune(')')
}
if f.underlying != nil {
fmt.Fprintf(&b, ": %s", f.underlying.Error())
}
return b.String()
}
func (f *failure) Format(state fmt.State, verb rune) {
if verb != 'v' { // %s
_, _ = io.WriteString(state, f.Error())
return
}
if state.Flag('#') { // %#v
// print original Go representation ignoring Format (this) function.
type stack struct {
underlying error
fields map[any]any
order []any
}
var tmp = stack(*f)
_, _ = fmt.Fprintf(state, "%#v", &tmp)
return
}
if !state.Flag('+') { // %v
_, _ = io.WriteString(state, f.Error())
return
}
var err error = f
for {
switch t := err.(type) {
case Failure:
cs := t.Value(KeyCallStack)
if cs != nil {
fmt.Fprintf(state, "%+v\n", cs.(CallStack).HeadFrame())
}
t.foreach(func(k, v any) {
if k == KeyCallStack {
return
}
state.Write([]byte(" "))
if ef, ok := v.(ErrorFormatter); ok {
ef.FormatError(state)
} else {
fmt.Fprint(state, v)
}
state.Write([]byte("\n"))
})
default:
fmt.Fprintf(state, "%T(%q)\n", err, err.Error())
}
err = ForceUnwrap(err)
if err == nil {
break
}
}
fmt.Fprint(state, "[CallStack]\n")
if cs := CallStackOf(f); cs != nil {
for _, f := range cs.Frames() {
fmt.Fprintf(state, " %+v\n", f)
}
}
}
func (f *failure) As(target any) bool {
targetType := reflect.TypeOf(target)
for _, key := range f.order {
f := f.fields[key]
fType := reflect.TypeOf(f)
if targetType.Kind() == reflect.Ptr {
targetElemType := targetType.Elem()
// Set the value if:
// 1. target is the same type.
// 2. target is interface and field is assignable it.
// Check whether assignable only if target is interface, to prevent unexpected assigning like failure.Context to map[string]string.
if fType == targetElemType || (targetElemType.Kind() == reflect.Interface && fType.AssignableTo(targetElemType)) {
targetVal := reflect.ValueOf(target)
if targetVal.IsNil() {
panic("failure: target cannot be nil")
}
targetVal.Elem().Set(reflect.ValueOf(f))
return true
}
}
if as, ok := f.(interface{ As(any) bool }); ok {
if as.As(target) {
return true
}
}
}
return false
}
func (f *failure) Value(key any) any {
return f.fields[key]
}
func (f *failure) foreach(cb func(k, v any)) {
for _, k := range f.order {
v := f.fields[k]
cb(k, v)
}
}
// Code represents an error code. Any comparable type can be used as an error code.
type Code comparable
// Field represents an error field. Implement this interface to define your own
// error fields and attach them to your errors.
type Field interface {
SetErrorField(FieldSetter)
}
var _ = []Field{
Context{},
codeField{},
Message(""),
CallStack{},
}
// FieldSetter is used by Field to set key-value pairs to an error.
type FieldSetter interface {
Set(key, value any)
}
var _ FieldSetter = (*asSetter)(nil)
// ErrorFormatter is an interface for formatting errors. Implement this interface
// to format errors in custom ways.
type ErrorFormatter interface {
FormatError(ErrorWriter)
}
var _ ErrorFormatter = Context{}
// ErrorWriter is used by ErrorFormatter to write errors with custom formats.
// It may have additional fields to specify output format in the future.
type ErrorWriter interface {
io.Writer
}
// New creates a new error with the provided error code and optional fields.
func New[C Code](c C, fields ...Field) error {
return newFailure(nil, c, fields)
}
// Translate creates a new error by translating the error code of an existing error.
// It wraps the original error with the new error code and optional fields.
func Translate[C Code](err error, c C, fields ...Field) error {
return newFailure(err, c, fields)
}
// Wrap creates a new error by wrapping an existing error with optional fields.
// It does not change the error code of the original error.
func Wrap(err error, fields ...Field) error {
if err == nil {
return nil
}
return newFailure(err, nil, fields)
}
// Unexpected creates a new error with the provided text and optional fields. Use this
// function when you want to create without an error code. This function should only be
// used when the error is not expected to occur.
func Unexpected(text string, fields ...Field) error {
return newFailure(errors.New(text), nil, fields)
}
// MarkUnexpected creates a new error that cannot be unwrapped using the standard Unwrap
// method. Use this function when you want to prevent propagating data like error
// codes or context to the caller. However, using ForceUnwrap will still allow
// retrieving the original error.
func MarkUnexpected(err error, fields ...Field) error {
return newFailure(opaque{err}, nil, fields)
}
type opaque struct {
error
}
func (opaque) Unwrap() error {
return nil
}
func (o opaque) ForceUnwrap() error {
return o.error
}