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