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