-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors.go
More file actions
373 lines (292 loc) · 7.31 KB
/
errors.go
File metadata and controls
373 lines (292 loc) · 7.31 KB
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Package ewrap provides enhanced error handling capabilities with stack traces,
// error wrapping, custom error types, and logging integration.
package ewrap
import (
"errors"
"fmt"
"maps"
"runtime"
"strings"
"sync"
"github.com/hyp3rd/ewrap/internal/logger"
)
const (
baseLogDataSize = 4 // error, msg, stack, and potentially cause
runtimeCallers = 3
)
// Error represents a custom error type with stack trace and metadata.
type Error struct {
msg string
cause error
stack []uintptr
metadata map[string]any
logger logger.Logger
observer Observer
mu sync.RWMutex // Protects metadata, logger, and observer
}
// Option defines the signature for configuration options.
type Option func(*Error)
// WithLogger sets a logger for the error.
func WithLogger(log logger.Logger) Option {
return func(err *Error) {
err.mu.Lock()
err.logger = log
err.mu.Unlock()
// Log error creation if logger is available
if log != nil {
log.Debug("error created",
"message", err.msg,
"stack", err.Stack(),
)
}
}
}
// WithObserver sets an observer for the error.
func WithObserver(observer Observer) Option {
return func(err *Error) {
err.mu.Lock()
err.observer = observer
err.mu.Unlock()
}
}
// New creates a new Error with a stack trace and applies the provided options.
func New(msg string, opts ...Option) *Error {
err := &Error{
msg: msg,
stack: CaptureStack(),
metadata: make(map[string]any),
}
for _, opt := range opts {
opt(err)
}
return err
}
// Newf creates a new Error with a formatted message and applies the provided options.
func Newf(format string, args ...any) *Error {
return New(fmt.Sprintf(format, args...))
}
// Wrap wraps an existing error with additional context and stack trace.
func Wrap(err error, msg string, opts ...Option) *Error {
if err == nil {
return nil
}
var (
stack []uintptr
metadata map[string]any
observer Observer
log logger.Logger
wrappedErr *Error
)
// If the error is already wrapped, preserve its stack trace and metadata
if errors.As(err, &wrappedErr) {
wrappedErr.mu.RLock()
stack = wrappedErr.stack
// Clone metadata map using maps.Clone for simplicity
metadata = maps.Clone(wrappedErr.metadata)
observer = wrappedErr.observer
log = wrappedErr.logger
wrappedErr.mu.RUnlock()
} else {
stack = CaptureStack()
metadata = make(map[string]any)
}
wrapped := &Error{
msg: msg,
cause: err,
stack: stack,
metadata: metadata,
observer: observer,
logger: log,
}
for _, opt := range opts {
opt(wrapped)
}
return wrapped
}
// Wrapf wraps an error with a formatted message.
func Wrapf(err error, format string, args ...any) *Error {
if err == nil {
return nil
}
return Wrap(err, fmt.Sprintf(format, args...))
}
// Error implements the error interface.
func (e *Error) Error() string {
if e.cause != nil {
return fmt.Sprintf("%s: %v", e.msg, e.cause)
}
return e.msg
}
// Cause returns the underlying cause of the error.
func (e *Error) Cause() error {
return e.cause
}
// WithMetadata adds metadata to the error.
func (e *Error) WithMetadata(key string, value any) *Error {
e.mu.Lock()
e.metadata[key] = value
if e.logger != nil {
e.logger.Debug("metadata added",
"key", key,
"value", value,
"error", e.msg,
)
}
e.mu.Unlock()
return e
}
// WithContext adds context information to the error.
func (e *Error) WithContext(ctx *ErrorContext) *Error {
e.mu.Lock()
defer e.mu.Unlock()
e.metadata["error_context"] = ctx
if e.logger != nil {
e.logger.Debug("context added",
"context", ctx,
"error", e.msg,
)
}
return e
}
// WithRecoverySuggestion attaches recovery guidance to the error.
func WithRecoverySuggestion(rs *RecoverySuggestion) Option {
return func(err *Error) {
err.mu.Lock()
err.metadata["recovery_suggestion"] = rs
err.mu.Unlock()
if err.logger != nil && rs != nil {
logData := []any{"message", rs.Message}
if len(rs.Actions) > 0 {
logData = append(logData, "actions", rs.Actions)
}
if rs.Documentation != "" {
logData = append(logData, "documentation", rs.Documentation)
}
err.logger.Info("recovery suggestion added", logData...)
}
}
}
// GetMetadata retrieves metadata from the error.
func (e *Error) GetMetadata(key string) (any, bool) {
e.mu.RLock()
defer e.mu.RUnlock()
val, ok := e.metadata[key]
return val, ok
}
// GetMetadataValue retrieves metadata and attempts to cast it to type T.
func GetMetadataValue[T any](e *Error, key string) (T, bool) {
e.mu.RLock()
defer e.mu.RUnlock()
var zero T
val, ok := e.metadata[key]
if !ok {
return zero, false
}
typedVal, ok := val.(T)
if !ok {
return zero, false
}
return typedVal, true
}
// GetErrorContext retrieves the context from the error.
func (e *Error) GetErrorContext() *ErrorContext {
e.mu.RLock()
defer e.mu.RUnlock()
if ctx, ok := e.metadata["error_context"].(*ErrorContext); ok {
return ctx
}
return nil
}
// Stack returns the stack trace as a string.
func (e *Error) Stack() string {
var builder strings.Builder
frames := runtime.CallersFrames(e.stack)
for {
frame, more := frames.Next()
// Skip runtime frames and error package frames
if !strings.Contains(frame.File, "runtime/") && !strings.Contains(frame.File, "ewrap/errors.go") {
_, _ = fmt.Fprintf(&builder, "%s:%d - %s\n", frame.File, frame.Line, frame.Function)
}
if !more {
break
}
}
return builder.String()
}
// Log logs the error using the configured logger.
func (e *Error) Log() {
e.mu.RLock()
observer := e.observer
log := e.logger
e.mu.RUnlock()
if observer != nil {
observer.RecordError(e.msg)
}
if log == nil {
return
}
// Create a metadata map for logging
logData := make([]any, 0, len(e.metadata)*2+baseLogDataSize)
logData = append(logData, "error", e.msg)
if e.cause != nil {
logData = append(logData, "cause", e.cause.Error())
}
logData = append(logData, "stack", e.Stack())
e.mu.RLock()
for key, val := range e.metadata {
if key == "recovery_suggestion" {
logData = e.appendRecoverySuggestion(logData, val)
continue
}
logData = append(logData, key, val)
}
e.mu.RUnlock()
log.Error("error occurred", logData...)
}
// CaptureStack captures the current stack trace.
func CaptureStack() []uintptr {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(runtimeCallers, pcs[:])
return pcs[:n]
}
// Is reports whether target matches err in the error chain.
func (e *Error) Is(target error) bool {
if target == nil {
return false
}
err := e
for err != nil {
if err.msg == target.Error() {
return true
}
if err.cause == nil {
return false
}
if causeErr, ok := err.cause.(*Error); ok {
err = causeErr
continue
}
return err.cause.Error() == target.Error()
}
return false
}
// Unwrap provides compatibility with Go 1.13 error chains.
func (e *Error) Unwrap() error {
return e.cause
}
// appendRecoverySuggestion extracts recovery suggestion data for logging.
func (*Error) appendRecoverySuggestion(logData []any, val any) []any {
rs, ok := val.(*RecoverySuggestion)
if !ok {
return logData
}
logData = append(logData, "recovery_message", rs.Message)
if len(rs.Actions) > 0 {
logData = append(logData, "recovery_actions", rs.Actions)
}
if rs.Documentation != "" {
logData = append(logData, "recovery_documentation", rs.Documentation)
}
return logData
}