create-wervt 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,468 @@
1
+ # Structured Errors Guide
2
+
3
+ Structured errors provide context that helps developers understand **what** happened, **why** it happened, and **how to fix it**.
4
+
5
+ ## The Problem with Generic Errors
6
+
7
+ ```typescript
8
+ // ❌ Useless errors
9
+ throw new Error('Something went wrong')
10
+ throw new Error('Failed')
11
+ throw new Error('Invalid input')
12
+
13
+ // ❌ Missing context
14
+ throw new Error('Payment failed') // Why? How do I fix it?
15
+ ```
16
+
17
+ When these errors reach your logs or monitoring, you have no idea:
18
+
19
+ - What actually failed
20
+ - Why it failed
21
+ - How to fix it
22
+ - Where to find more information
23
+
24
+ ## Structured Error Anatomy
25
+
26
+ ```typescript
27
+ import { createError } from 'evlog'
28
+
29
+ throw createError({
30
+ message: 'Payment failed', // What happened
31
+ status: 402, // HTTP status code
32
+ why: 'Card declined by issuer', // Why it happened
33
+ fix: 'Try a different payment method', // How to fix it
34
+ link: 'https://docs.example.com/...', // More information
35
+ cause: originalError, // Original error
36
+ data: {
37
+ // Optional: extra payload for the client
38
+ orderId: 'ord_8x2k',
39
+ retryAfter: 30,
40
+ },
41
+ internal: {
42
+ // Optional: backend / logs only
43
+ correlationId: 'pay_abc',
44
+ processorCode: 'card_declined',
45
+ },
46
+ })
47
+ ```
48
+
49
+ ### `data` (client payload)
50
+
51
+ - Use `data` for values the client branches on, an order id, a retry deadline, a list of invalid fields. `why`, `fix`, and `link` stay for the strings a human reads.
52
+ - The payload is merged into the response body's `data` object next to `code`, `why`, `fix`, and `link`, and those four win on a key collision. Read it client-side as `parseError(error).data`.
53
+ - Same field name as h3's `createError({ data })`, and evlog's Nitro error handler forwards it for h3 errors too.
54
+
55
+ ### `internal` (backend-only)
56
+
57
+ - Use `internal` for IDs, gateway codes, or diagnostics that **must not** appear in HTTP error bodies or in client-side `parseError()` results.
58
+ - Access in server code via **`error.internal`**. Values are omitted from **`toJSON()`** and from framework serializers; they are included on wide events under **`error.internal`** when the error is captured with **`log.error()`** (or equivalent automatic capture).
59
+ - Stored with a non-enumerable symbol so `JSON.stringify(error)` does not leak `internal`; devtools may show it as `[Symbol(evlog.error.internal)]`.
60
+
61
+ ### Console Output (Development)
62
+
63
+ ```
64
+ Error: Payment failed
65
+ Why: Card declined by issuer
66
+ Fix: Try a different payment method
67
+ More info: https://docs.example.com/payments/declined
68
+
69
+ Caused by: StripeCardError: card_declined
70
+ ```
71
+
72
+ ### JSON Output (Production)
73
+
74
+ `EvlogError.toJSON()`, returned as-is by the Next.js handler:
75
+
76
+ ```json
77
+ {
78
+ "name": "EvlogError",
79
+ "message": "Payment failed",
80
+ "status": 402,
81
+ "data": {
82
+ "orderId": "ord_8x2k",
83
+ "retryAfter": 30,
84
+ "why": "Card declined by issuer",
85
+ "fix": "Try a different payment method",
86
+ "link": "https://docs.example.com/payments/declined"
87
+ },
88
+ "cause": {
89
+ "name": "StripeCardError",
90
+ "message": "card_declined"
91
+ }
92
+ }
93
+ ```
94
+
95
+ The Nitro, Nuxt, and SvelteKit handlers return a Nitro-shaped body instead, with `url`, `statusCode`, `statusText`, and `error: true` around the same `message`, `status`, and `data`. Every serializer agrees on the part clients read: `why`, `fix`, and `link` sit under `data`, not at the top level, and neither `internal` nor `stack` is ever included. On the client, `parseError()` flattens both shapes.
96
+
97
+ ## Field Guidelines
98
+
99
+ ### `message` - What Happened
100
+
101
+ User-facing description of what went wrong.
102
+
103
+ ```typescript
104
+ // ✅ Good - clear, actionable
105
+ message: 'Failed to sync repository'
106
+ message: 'Unable to process payment'
107
+ message: 'User not found'
108
+
109
+ // ❌ Bad - vague, unhelpful
110
+ message: 'Error'
111
+ message: 'Something went wrong'
112
+ message: 'Failed'
113
+ ```
114
+
115
+ ### `why` - Why It Happened
116
+
117
+ Technical explanation for debugging.
118
+
119
+ ```typescript
120
+ // ✅ Good - specific, technical
121
+ why: 'GitHub API rate limit exceeded (403)'
122
+ why: 'Card declined by issuer: insufficient_funds'
123
+ why: 'No user with ID "user_123" exists in database'
124
+
125
+ // ❌ Bad - just restating the message
126
+ why: 'It failed'
127
+ why: 'Error occurred'
128
+ ```
129
+
130
+ ### `fix` - How to Fix It
131
+
132
+ Actionable steps to resolve the issue.
133
+
134
+ ```typescript
135
+ // ✅ Good - specific actions
136
+ fix: 'Wait 1 hour or use a different API token'
137
+ fix: 'Use a different payment method or contact your bank'
138
+ fix: 'Check the user ID and try again'
139
+
140
+ // ❌ Bad - not actionable
141
+ fix: 'Fix the error'
142
+ fix: 'Try again'
143
+ ```
144
+
145
+ ### `link` - More Information
146
+
147
+ Documentation URL for detailed troubleshooting.
148
+
149
+ ```typescript
150
+ // ✅ Good - specific documentation
151
+ link: 'https://docs.github.com/en/rest/rate-limit'
152
+ link: 'https://docs.stripe.com/declines/codes'
153
+ link: 'https://your-app.com/docs/errors/user-not-found'
154
+ ```
155
+
156
+ ### `cause` - Original Error
157
+
158
+ The underlying error that triggered this one.
159
+
160
+ ```typescript
161
+ try {
162
+ await stripe.charges.create(...)
163
+ } catch (error) {
164
+ throw createError({
165
+ message: 'Payment failed',
166
+ why: `Stripe error: ${error.code}`,
167
+ fix: 'Contact support with error code',
168
+ cause: error, // Preserves original stack trace
169
+ })
170
+ }
171
+ ```
172
+
173
+ ## Common Error Patterns
174
+
175
+ ### API/External Service Errors
176
+
177
+ ```typescript
178
+ // Rate limiting
179
+ throw createError({
180
+ message: 'GitHub sync temporarily unavailable',
181
+ status: 429,
182
+ why: 'API rate limit exceeded (5000/hour)',
183
+ fix: 'Wait until rate limit resets or use authenticated requests',
184
+ link: 'https://docs.github.com/en/rest/rate-limit',
185
+ cause: error,
186
+ })
187
+
188
+ // Authentication
189
+ throw createError({
190
+ message: 'Unable to connect to Stripe',
191
+ status: 503,
192
+ why: 'Invalid API key provided',
193
+ fix: 'Check STRIPE_SECRET_KEY environment variable',
194
+ link: 'https://docs.stripe.com/keys',
195
+ cause: error,
196
+ })
197
+
198
+ // Network
199
+ throw createError({
200
+ message: 'Failed to fetch user data',
201
+ status: 504,
202
+ why: 'Connection timeout after 30s',
203
+ fix: 'Check network connectivity and try again',
204
+ cause: error,
205
+ })
206
+ ```
207
+
208
+ ### Validation Errors
209
+
210
+ ```typescript
211
+ // Missing required field
212
+ throw createError({
213
+ message: 'Invalid checkout request',
214
+ status: 400,
215
+ why: 'Required field "email" is missing',
216
+ fix: 'Include a valid email address in the request body',
217
+ link: 'https://your-api.com/docs/checkout#request-body',
218
+ })
219
+
220
+ // Invalid format
221
+ throw createError({
222
+ message: 'Invalid email format',
223
+ status: 422,
224
+ why: `"${email}" is not a valid email address`,
225
+ fix: 'Provide an email in the format user@example.com',
226
+ })
227
+
228
+ // Business rule violation
229
+ throw createError({
230
+ message: 'Cannot cancel subscription',
231
+ status: 409,
232
+ why: 'Subscription has already been cancelled',
233
+ fix: 'No action needed - subscription is already inactive',
234
+ })
235
+ ```
236
+
237
+ ### Database Errors
238
+
239
+ ```typescript
240
+ // Not found
241
+ throw createError({
242
+ message: 'User not found',
243
+ status: 404,
244
+ why: `No user with ID "${userId}" exists`,
245
+ fix: 'Verify the user ID is correct',
246
+ })
247
+
248
+ // Constraint violation
249
+ throw createError({
250
+ message: 'Cannot create duplicate account',
251
+ status: 409,
252
+ why: `User with email "${email}" already exists`,
253
+ fix: 'Use a different email or log in to existing account',
254
+ link: 'https://your-app.com/login',
255
+ })
256
+
257
+ // Connection
258
+ throw createError({
259
+ message: 'Database unavailable',
260
+ status: 503,
261
+ why: 'Connection pool exhausted',
262
+ fix: 'Reduce concurrent connections or increase pool size',
263
+ cause: error,
264
+ })
265
+ ```
266
+
267
+ ### Permission Errors
268
+
269
+ ```typescript
270
+ throw createError({
271
+ message: 'Access denied',
272
+ status: 403,
273
+ why: 'User lacks "admin" role required for this action',
274
+ fix: 'Contact an administrator to request access',
275
+ link: 'https://your-app.com/docs/permissions',
276
+ })
277
+ ```
278
+
279
+ ## Transformation Examples
280
+
281
+ ### Before: Generic Error
282
+
283
+ ```typescript
284
+ async function processPayment(cart, user) {
285
+ try {
286
+ return await stripe.charges.create({
287
+ amount: cart.total,
288
+ currency: 'usd',
289
+ source: user.paymentMethodId,
290
+ })
291
+ } catch (error) {
292
+ throw new Error('Payment failed') // ❌ No context
293
+ }
294
+ }
295
+ ```
296
+
297
+ ### After: Structured Error
298
+
299
+ ```typescript
300
+ async function processPayment(cart, user) {
301
+ try {
302
+ return await stripe.charges.create({
303
+ amount: cart.total,
304
+ currency: 'usd',
305
+ source: user.paymentMethodId,
306
+ })
307
+ } catch (error) {
308
+ throw createError({
309
+ message: 'Payment failed',
310
+ why: getStripeErrorReason(error),
311
+ fix: getStripeErrorFix(error),
312
+ link: 'https://docs.stripe.com/declines/codes',
313
+ cause: error,
314
+ })
315
+ }
316
+ }
317
+
318
+ function getStripeErrorReason(error) {
319
+ const reasons = {
320
+ card_declined: 'Card was declined by the issuer',
321
+ insufficient_funds: 'Card has insufficient funds',
322
+ expired_card: 'Card has expired',
323
+ // ...
324
+ }
325
+ return reasons[error.code] ?? `Stripe error: ${error.code}`
326
+ }
327
+
328
+ function getStripeErrorFix(error) {
329
+ const fixes = {
330
+ card_declined: 'Try a different payment method or contact your bank',
331
+ insufficient_funds: 'Use a different card or add funds',
332
+ expired_card: 'Update your card details with a valid expiration date',
333
+ // ...
334
+ }
335
+ return fixes[error.code] ?? 'Contact support with error code'
336
+ }
337
+ ```
338
+
339
+ ## Integration with Wide Events
340
+
341
+ Structured errors integrate seamlessly with wide events:
342
+
343
+ ```typescript
344
+ // server/api/checkout.post.ts
345
+ // Nuxt: useLogger is auto-imported, createError is not
346
+ // Nitro v3: import { useLogger } from 'evlog/nitro/v3'
347
+ // Nitro v2: import { useLogger } from 'evlog/nitro'
348
+ import { createError } from 'evlog'
349
+
350
+ export default defineEventHandler(async (event) => {
351
+ const log = useLogger(event)
352
+
353
+ try {
354
+ // ... business logic ...
355
+ } catch (error) {
356
+ // EvlogError fields are automatically captured
357
+ log.error(error, { step: 'payment' })
358
+ throw createError({
359
+ message: 'Payment failed',
360
+ why: error.message,
361
+ fix: 'Try a different payment method',
362
+ })
363
+ }
364
+ // emit() called automatically
365
+ })
366
+ ```
367
+
368
+ The wide event will include:
369
+
370
+ ```json
371
+ {
372
+ "error": {
373
+ "name": "EvlogError",
374
+ "message": "Payment failed",
375
+ "why": "Card declined by issuer",
376
+ "fix": "Try a different payment method",
377
+ "link": "https://docs.stripe.com/declines/codes",
378
+ "internal": {
379
+ "stripeRequestId": "req_123"
380
+ }
381
+ },
382
+ "step": "payment"
383
+ }
384
+ ```
385
+
386
+ If you use `createError({ ..., internal: { ... } })` without calling `log.error(error)` yourself, framework integrations that attach thrown errors to the wide event still merge **`internal`** into **`error.internal`** on emit.
387
+
388
+ ## Best Practices
389
+
390
+ ### Do
391
+
392
+ - Always provide `message` and `why` at minimum
393
+ - Include `fix` when there's an actionable solution
394
+ - Add `link` to documentation for complex errors
395
+ - Preserve `cause` when wrapping errors
396
+ - Be specific about what failed and why
397
+ - Put operator-only or sensitive diagnostics in `internal`, not in `why`/`fix`/`message`
398
+
399
+ ### Don't
400
+
401
+ - Use generic messages like "Error" or "Failed"
402
+ - Leak sensitive data (passwords, tokens, PII)
403
+ - Expect `internal` in HTTP JSON or in `parseError()`. It is for server logs and drains only
404
+ - Make `why` and `message` identical
405
+ - Suggest fixes that aren't actually possible
406
+ - Create errors without any context
407
+
408
+ ## Nitro Compatibility
409
+
410
+ evlog errors work with any Nitro-powered framework. When thrown in an API route, the error is automatically converted to an HTTP response:
411
+
412
+ ```typescript
413
+ // Backend - just throw
414
+ throw createError({
415
+ message: 'Payment failed',
416
+ status: 402,
417
+ why: 'Card declined',
418
+ fix: 'Try another card',
419
+ link: 'https://docs.example.com/payments',
420
+ })
421
+
422
+ // HTTP Response:
423
+ // Status: 402
424
+ // Body: {
425
+ // statusCode: 402,
426
+ // message: "Payment failed",
427
+ // data: { why: "Card declined", fix: "Try another card", link: "..." }
428
+ // }
429
+ ```
430
+
431
+ ### Frontend Integration
432
+
433
+ Use `parseError()` to extract all fields at the top level:
434
+
435
+ ```typescript
436
+ import { parseError } from 'evlog'
437
+
438
+ try {
439
+ await $fetch('/api/checkout')
440
+ } catch (err) {
441
+ const error = parseError(err)
442
+
443
+ // Direct access: error.message, error.why, error.fix, error.link
444
+ toast.add({
445
+ title: error.message,
446
+ description: error.why,
447
+ color: 'error',
448
+ actions: error.link
449
+ ? [{ label: 'Learn more', onClick: () => window.open(error.link) }]
450
+ : undefined,
451
+ })
452
+
453
+ if (error.fix) console.info(`💡 Fix: ${error.fix}`)
454
+ }
455
+ ```
456
+
457
+ **The difference**: A generic error shows "An error occurred". A structured error shows the message, explains why, suggests a fix, and links to documentation.
458
+
459
+ ## Error Message Templates
460
+
461
+ Common patterns, with the fields adapted to each case:
462
+
463
+ | Pattern | Status | Fields |
464
+ | ------------------------ | ------ | ------------------------------------------------------------------------------------------- |
465
+ | Resource not found | 404 | `why`: what's missing, `fix`: verify identifier |
466
+ | External service failure | 503 | `why`: service error, `fix`: actionable step, `link`: service docs, `cause`: original error |
467
+ | Validation failure | 400 | `why`: what's invalid, `fix`: expected format |
468
+ | Permission denied | 403 | `why`: what's required, `fix`: how to get access |