-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.go
More file actions
174 lines (149 loc) · 4.51 KB
/
format.go
File metadata and controls
174 lines (149 loc) · 4.51 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
package ewrap
import (
"errors"
"fmt"
"time"
"github.com/goccy/go-json"
"gopkg.in/yaml.v3"
)
// ErrorOutput represents a formatted error output structure that can be
// serialized to various formats like JSON and YAML.
type ErrorOutput struct {
// Message contains the main error message
Message string `json:"message" yaml:"message"`
// Timestamp indicates when the error occurred
Timestamp string `json:"timestamp" yaml:"timestamp"`
// Type categorizes the error
Type string `json:"type" yaml:"type"`
// Severity indicates the error's impact level
Severity string `json:"severity" yaml:"severity"`
// Stack contains the error stack trace
Stack string `json:"stack" yaml:"stack"`
// Cause contains the underlying error if any
Cause *ErrorOutput `json:"cause,omitempty" yaml:"cause,omitempty"`
// Context contains additional error context
Context map[string]any `json:"context,omitempty" yaml:"context,omitempty"`
// Metadata contains user-defined metadata
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata,omitempty"`
// Recovery provides guidance on resolving the error
Recovery *RecoverySuggestion `json:"recovery,omitempty" yaml:"recovery,omitempty"`
}
// FormatOption defines formatting options for error output.
type FormatOption func(*ErrorOutput)
// WithTimestampFormat allows customizing the timestamp format in the output.
func WithTimestampFormat(format string) FormatOption {
return func(eo *ErrorOutput) {
if format == "" {
return
}
// Attempt to parse existing timestamp and reformat
t, err := time.Parse(time.RFC3339, eo.Timestamp)
if err == nil {
eo.Timestamp = t.Format(format)
}
}
}
// WithStackTrace controls whether to include the stack trace in the output.
func WithStackTrace(include bool) FormatOption {
return func(eo *ErrorOutput) {
if !include {
eo.Stack = ""
}
}
}
// toErrorOutput converts an Error to ErrorOutput format.
func (e *Error) toErrorOutput(opts ...FormatOption) *ErrorOutput {
e.mu.RLock()
defer e.mu.RUnlock()
// Extract error context if available
var (
ctx *ErrorContext
contextMap map[string]any
recovery *RecoverySuggestion
)
if rawCtx, ok := e.metadata["error_context"]; ok {
if ctx, ok = rawCtx.(*ErrorContext); ok {
contextMap = map[string]any{
"request_id": ctx.RequestID,
"user": ctx.User,
"component": ctx.Component,
"operation": ctx.Operation,
"file": ctx.File,
"line": ctx.Line,
"environment": ctx.Environment,
}
}
}
if rawRec, ok := e.metadata["recovery_suggestion"]; ok {
recovery, ok = rawRec.(*RecoverySuggestion)
if !ok {
recovery = nil
}
}
// Create base output structure
output := &ErrorOutput{
Message: e.msg,
Timestamp: time.Now().Format(time.RFC3339),
Type: "unknown",
Severity: "error",
Stack: e.Stack(),
Context: contextMap,
Metadata: make(map[string]any),
Recovery: recovery,
}
// Copy metadata excluding internal keys
copyMetadata(e, output)
// Set error type and severity if available
if ctx != nil {
output.Type = ctx.Type.String()
output.Severity = ctx.Severity.String()
}
// Handle wrapped errors
if e.cause != nil {
var wrappedErr *Error
if errors.As(e.cause, &wrappedErr) {
output.Cause = wrappedErr.toErrorOutput(opts...)
} else {
output.Cause = &ErrorOutput{
Message: e.cause.Error(),
Type: "unknown",
Severity: "error",
}
}
}
// Apply formatting options
applyFormatOptions(output, opts...)
return output
}
// applyFormatOptions applies the given formatting options to the ErrorOutput.
func applyFormatOptions(output *ErrorOutput, opts ...FormatOption) {
for _, opt := range opts {
opt(output)
}
}
// copyMetadata copies user-defined metadata from the Error to the ErrorOutput.
func copyMetadata(e *Error, output *ErrorOutput) {
for k, v := range e.metadata {
if k != "error_context" && k != "recovery_suggestion" {
output.Metadata[k] = v
}
}
}
// ToJSON converts the error to a JSON string.
func (e *Error) ToJSON(opts ...FormatOption) (string, error) {
output := e.toErrorOutput(opts...)
data, err := json.MarshalIndent(output, "", " ")
if err != nil {
return "", fmt.Errorf("failed to marshal error to JSON: %w", err)
}
return string(data), nil
}
// ToYAML converts the error to a YAML string.
func (e *Error) ToYAML(opts ...FormatOption) (string, error) {
output := e.toErrorOutput(opts...)
data, err := yaml.Marshal(output)
if err != nil {
return "", fmt.Errorf("failed to marshal error to YAML: %w", err)
}
return string(data), nil
}