-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
412 lines (347 loc) · 15.4 KB
/
example_test.go
File metadata and controls
412 lines (347 loc) · 15.4 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package trogonerror_test
import (
"fmt"
"time"
"github.com/TrogonStack/trogonerror"
)
func ExampleNewError() {
err := trogonerror.NewError("shopify.users", "NOT_FOUND",
trogonerror.WithCode(trogonerror.CodeNotFound),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "userId", "gid://shopify/Customer/1234567890"))
fmt.Println(err.Error())
fmt.Println(err.Domain())
fmt.Println(err.Reason())
// Output:
// resource not found
// visibility: INTERNAL
// domain: shopify.users
// reason: NOT_FOUND
// code: NOT_FOUND
// metadata:
// - userId: gid://shopify/Customer/1234567890 visibility=PUBLIC
// shopify.users
// NOT_FOUND
}
func ExampleErrorTemplate() {
template := trogonerror.NewErrorTemplate("shopify.users", "NOT_FOUND",
trogonerror.TemplateWithCode(trogonerror.CodeNotFound))
err := template.NewError(
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "userId", "gid://shopify/Customer/1234567890"))
fmt.Println(err.Error())
fmt.Println(err.Domain())
fmt.Println(err.Reason())
// Output:
// resource not found
// visibility: INTERNAL
// domain: shopify.users
// reason: NOT_FOUND
// code: NOT_FOUND
// metadata:
// - userId: gid://shopify/Customer/1234567890 visibility=PUBLIC
// shopify.users
// NOT_FOUND
}
func ExampleWithCause() {
dbErr := trogonerror.NewError("shopify.database", "CONNECTION_FAILED",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "host", "postgres-primary.shopify.com"))
serviceErr := trogonerror.NewError("shopify.users", "USER_FETCH_FAILED",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithMessage("Failed to fetch user data"),
trogonerror.WithCause(dbErr))
fmt.Println(serviceErr.Error())
fmt.Println(len(serviceErr.Causes()))
fmt.Println(serviceErr.Causes()[0].Domain())
// Output:
// Failed to fetch user data
// visibility: INTERNAL
// domain: shopify.users
// reason: USER_FETCH_FAILED
// code: INTERNAL
// 1
// shopify.database
}
func ExampleCode_methods() {
code := trogonerror.CodeNotFound
fmt.Println(code.String())
fmt.Println(code.HttpStatusCode())
// Output:
// NOT_FOUND
// 404
}
func ExampleNewError_basic() {
err := trogonerror.NewError("shopify.users", "NOT_FOUND",
trogonerror.WithCode(trogonerror.CodeNotFound),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "userId", "gid://shopify/Customer/1234567890"))
fmt.Println("Error message:", err.Error())
fmt.Println("Domain:", err.Domain())
fmt.Println("Reason:", err.Reason())
fmt.Println("Code:", err.Code().String())
// Output:
// Error message: resource not found
// visibility: INTERNAL
// domain: shopify.users
// reason: NOT_FOUND
// code: NOT_FOUND
// metadata:
// - userId: gid://shopify/Customer/1234567890 visibility=PUBLIC
// Domain: shopify.users
// Reason: NOT_FOUND
// Code: NOT_FOUND
}
func ExampleErrorTemplate_production() {
var (
ErrUserNotFound = trogonerror.NewErrorTemplate("shopify.users", "NOT_FOUND",
trogonerror.TemplateWithCode(trogonerror.CodeNotFound),
trogonerror.TemplateWithCode(trogonerror.CodeNotFound))
ErrInvalidInput = trogonerror.NewErrorTemplate("shopify.validation", "INVALID_INPUT",
trogonerror.TemplateWithCode(trogonerror.CodeInvalidArgument))
)
userErr := ErrUserNotFound.NewError(
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "userId", "gid://shopify/Customer/4567890123"))
inputErr := ErrInvalidInput.NewError(
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "fieldName", "email"),
trogonerror.WithSubject("/email"))
fmt.Println("User error:", userErr.Domain(), userErr.Reason())
fmt.Println("Input error:", inputErr.Domain(), inputErr.Reason())
// Output:
// User error: shopify.users NOT_FOUND
// Input error: shopify.validation INVALID_INPUT
}
func ExampleNewError_richMetadata() {
err := trogonerror.NewError("shopify.payments", "PAYMENT_DECLINED",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithMessage("Payment processing failed due to upstream service error"),
trogonerror.WithVisibility(trogonerror.VisibilityPrivate),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "paymentId", "pay_2024_01_15_abc123def456"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "amount", "299.99"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "currency", "USD"),
trogonerror.WithMetadataValue(trogonerror.VisibilityInternal, "merchantId", "gid://shopify/Shop/1234567890"),
trogonerror.WithSubject("/payment/amount"),
trogonerror.WithTime(time.Date(2024, 1, 15, 14, 30, 45, 0, time.UTC)),
trogonerror.WithSourceID("payment-gateway-prod-01"))
fmt.Printf("Payment ID: %s\n", err.Metadata()["paymentId"].Value())
fmt.Printf("Currency: %s\n", err.Metadata()["currency"].Value())
fmt.Printf("Subject: %s\n", err.Subject())
// Output:
// Payment ID: pay_2024_01_15_abc123def456
// Currency: USD
// Subject: /payment/amount
}
func ExampleWithStackTrace_debugging() {
// Error with stack trace for debugging
err := trogonerror.NewError("shopify.database", "QUERY_TIMEOUT",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithStackTrace(),
trogonerror.WithDebugDetail("Database query failed with timeout"),
trogonerror.WithMetadataValue(trogonerror.VisibilityInternal, "query", "SELECT * FROM customers WHERE id = $1"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "requestId", "req_2024_01_15_db_query_abc123"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "duration", "1.5s"))
fmt.Printf("Has debug info: %v\n", err.DebugInfo() != nil)
if err.DebugInfo() != nil {
fmt.Printf("Debug detail: %s\n", err.DebugInfo().Detail())
fmt.Printf("Stack entries count: %d\n", len(err.DebugInfo().StackEntries()))
}
// Output:
// Has debug info: true
// Debug detail: Database query failed with timeout
// Stack entries count: 9
}
func ExampleWithCause_errorChaining() {
dbErr := trogonerror.NewError("shopify.database", "CONNECTION_FAILED",
trogonerror.WithCode(trogonerror.CodeUnavailable),
trogonerror.WithMessage("Database connection timeout"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "host", "postgres-primary.shopify.com"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "port", "5432"))
serviceErr := trogonerror.NewError("shopify.users", "USER_FETCH_FAILED",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithMessage("Failed to fetch user data"),
trogonerror.WithCause(dbErr))
fmt.Printf("Service error: %s\n", serviceErr.Reason())
fmt.Printf("Has causes: %v\n", len(serviceErr.Causes()) > 0)
if len(serviceErr.Causes()) > 0 {
fmt.Printf("Root cause: %s\n", serviceErr.Causes()[0].Reason())
fmt.Printf("Root cause domain: %s\n", serviceErr.Causes()[0].Domain())
}
// Output:
// Service error: USER_FETCH_FAILED
// Has causes: true
// Root cause: CONNECTION_FAILED
// Root cause domain: shopify.database
}
func ExampleWithRetryInfoDuration_retryLogic() {
// Error with retry information for rate limiting
err := trogonerror.NewError("shopify.api", "RATE_LIMIT_EXCEEDED",
trogonerror.WithCode(trogonerror.CodeResourceExhausted),
trogonerror.WithMessage("API rate limit exceeded"),
trogonerror.WithRetryInfoDuration(60*time.Second),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "limit", "100"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "timeWindow", "1m"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "remaining", "0"))
if retryInfo := err.RetryInfo(); retryInfo != nil {
if retryOffset := retryInfo.RetryOffset(); retryOffset != nil {
fmt.Printf("Retry after: %s\n", retryOffset.String())
}
}
fmt.Printf("Rate limit: %s\n", err.Metadata()["limit"].Value())
fmt.Printf("Window: %s\n", err.Metadata()["timeWindow"].Value())
// Output:
// Retry after: 1m0s
// Rate limit: 100
// Window: 1m
}
func ExampleWithRetryTime_absoluteRetry() {
retryTime := time.Date(2024, 1, 15, 14, 35, 0, 0, time.UTC)
err := trogonerror.NewError("shopify.maintenance", "SERVICE_UNAVAILABLE",
trogonerror.WithCode(trogonerror.CodeUnavailable),
trogonerror.WithMessage("Service temporarily unavailable for maintenance"),
trogonerror.WithRetryTime(retryTime),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "maintenanceWindow", "30min"))
if retryInfo := err.RetryInfo(); retryInfo != nil {
if retryTime := retryInfo.RetryTime(); retryTime != nil {
fmt.Printf("Retry at: %s\n", retryTime.Format("2006-01-02 15:04:05 UTC"))
}
}
fmt.Printf("Maintenance window: %s\n", err.Metadata()["maintenanceWindow"].Value())
// Output:
// Retry at: 2024-01-15 14:35:00 UTC
// Maintenance window: 30min
}
func ExampleWithHelpLink_documentation() {
// Error with help links for user guidance
err := trogonerror.NewError("shopify.users", "INVALID_EMAIL",
trogonerror.WithCode(trogonerror.CodeInvalidArgument),
trogonerror.WithMessage("Email address format is invalid"),
trogonerror.WithSubject("/email"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "fieldName", "email"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "providedValue", "invalid-email"),
trogonerror.WithHelpLink("Fix Email", "https://admin.shopify.com/customers/1234567890/edit#email"),
trogonerror.WithHelpLink("Contact Support", "https://admin.shopify.com/support/new?customer_id=1234567890"))
if help := err.Help(); help != nil {
fmt.Printf("Help links available: %d\n", len(help.Links()))
for _, link := range help.Links() {
fmt.Printf("- %s: %s\n", link.Description(), link.URL())
}
}
// Output:
// Help links available: 2
// - Fix Email: https://admin.shopify.com/customers/1234567890/edit#email
// - Contact Support: https://admin.shopify.com/support/new?customer_id=1234567890
}
func ExampleWithLocalizedMessage_internationalization() {
err := trogonerror.NewError("shopify.users", "NOT_FOUND",
trogonerror.WithCode(trogonerror.CodeNotFound),
trogonerror.WithLocalizedMessage("es-ES", "Usuario no encontrado"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "userId", "gid://shopify/Customer/7890123456"))
fmt.Printf("Default message: %s\n", err.Message())
if localizedMsg := err.LocalizedMessage(); localizedMsg != nil {
fmt.Printf("Localized (%s): %s\n", localizedMsg.Locale(), localizedMsg.Message())
}
// Output:
// Default message: resource not found
// Localized (es-ES): Usuario no encontrado
}
func ExampleCode_utilities() {
// Working with error codes
code := trogonerror.CodeNotFound
fmt.Printf("Code string: %s\n", code.String())
fmt.Printf("HTTP status: %d\n", code.HttpStatusCode())
fmt.Printf("Default message: %s\n", code.Message())
err := trogonerror.NewError("shopify.core", "INVALID_REQUEST", trogonerror.WithCode(trogonerror.CodeInvalidArgument))
if err.Code() == trogonerror.CodeInvalidArgument {
fmt.Println("This is an invalid argument error")
}
// Output:
// Code string: NOT_FOUND
// HTTP status: 404
// Default message: resource not found
// This is an invalid argument error
}
func ExampleWithWrap_standardErrors() {
originalErr := fmt.Errorf("connection timeout after 30s")
wrappedErr := trogonerror.NewError("shopify.database", "CONNECTION_TIMEOUT",
trogonerror.WithCode(trogonerror.CodeUnavailable),
trogonerror.WithWrap(originalErr),
trogonerror.WithErrorMessage(originalErr),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "timeout", "30s"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "host", "postgres-primary.shopify.com"))
fmt.Printf("Wrapped error domain: %s\n", wrappedErr.Domain())
fmt.Printf("Wrapped error reason: %s\n", wrappedErr.Reason())
fmt.Printf("Original message preserved: %v\n", wrappedErr.Message() == originalErr.Error())
// Output:
// Wrapped error domain: shopify.database
// Wrapped error reason: CONNECTION_TIMEOUT
// Original message preserved: true
}
func ExampleTrogonError_visibilityControl() {
// Demonstrate visibility controls
err := trogonerror.NewError("shopify.auth", "ACCESS_DENIED",
trogonerror.WithCode(trogonerror.CodePermissionDenied),
trogonerror.WithVisibility(trogonerror.VisibilityPublic),
trogonerror.WithMetadataValue(trogonerror.VisibilityInternal, "userId", "gid://shopify/Customer/1234567890"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPrivate, "resource", "/admin/customers"),
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "action", "DELETE"))
fmt.Printf("Error visibility: %s\n", err.Visibility().String())
// Show metadata with different visibility levels in alphabetical order
metadataKeys := []string{"action", "resource", "userId"}
for _, key := range metadataKeys {
if value, exists := err.Metadata()[key]; exists {
fmt.Printf("Metadata %s (%s): %s\n", key, value.Visibility().String(), value.Value())
}
}
// Output:
// Error visibility: PUBLIC
// Metadata action (PUBLIC): DELETE
// Metadata resource (PRIVATE): /admin/customers
// Metadata userId (INTERNAL): gid://shopify/Customer/1234567890
}
func ExampleWithMetadataValuef_formattedValues() {
// Using printf-style formatting for metadata values
userID := "1234567890"
orderID := "5432109876"
amount := 29999 // cents
err := trogonerror.NewError("shopify.orders", "ORDER_PROCESSING_FAILED",
trogonerror.WithCode(trogonerror.CodeInternal),
trogonerror.WithMetadataValuef(trogonerror.VisibilityPublic, "customerId", "gid://shopify/Customer/%s", userID),
trogonerror.WithMetadataValuef(trogonerror.VisibilityPublic, "orderId", "gid://shopify/Order/%s", orderID),
trogonerror.WithMetadataValuef(trogonerror.VisibilityPublic, "amount", "$%.2f", float64(amount)/100),
trogonerror.WithMetadataValuef(trogonerror.VisibilityInternal, "requestId", "req_%s_%s", userID, orderID))
fmt.Printf("Customer ID: %s\n", err.Metadata()["customerId"].Value())
fmt.Printf("Order ID: %s\n", err.Metadata()["orderId"].Value())
fmt.Printf("Amount: %s\n", err.Metadata()["amount"].Value())
fmt.Printf("Request ID: %s\n", err.Metadata()["requestId"].Value())
// Output:
// Customer ID: gid://shopify/Customer/1234567890
// Order ID: gid://shopify/Order/5432109876
// Amount: $299.99
// Request ID: req_1234567890_5432109876
}
func ExampleAs_idiomaticErrorHandling() {
// Define error templates (typically done at package level)
var ErrInsufficientStock = trogonerror.NewErrorTemplate("inventory", "INSUFFICIENT_STOCK",
trogonerror.TemplateWithCode(trogonerror.CodeResourceExhausted))
// Simulate an error from inventory service
inventoryErr := ErrInsufficientStock.NewError(
trogonerror.WithMetadataValue(trogonerror.VisibilityPublic, "product_id", "prod_12345"))
// Old verbose pattern:
// if inventory.ErrInsufficientStock.Is(err) {
// var trogonErr *trogonerror.TrogonError
// if errors.As(err, &trogonErr) {
// return nil, trogonErr.WithChanges(...)
// }
// }
// New idiomatic pattern using As:
if trogonErr, ok := trogonerror.As(inventoryErr, ErrInsufficientStock); ok {
modifiedErr := trogonErr.WithChanges(
trogonerror.WithChangeMetadataValue(trogonerror.VisibilityPublic, "order_id", "order_789"),
trogonerror.WithChangeMetadataValue(trogonerror.VisibilityPublic, "requested_quantity", "10"),
)
fmt.Printf("Modified error domain: %s\n", modifiedErr.Domain())
fmt.Printf("Order ID: %s\n", modifiedErr.Metadata()["order_id"].Value())
fmt.Printf("Requested quantity: %s\n", modifiedErr.Metadata()["requested_quantity"].Value())
}
// Output:
// Modified error domain: inventory
// Order ID: order_789
// Requested quantity: 10
}