also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,605 +0,0 @@ | ||
| 1 | # Error Handling | |
| 2 | ||
| 3 | This guide covers error handling patterns, debugging techniques, and best practices for managing errors in your Stacks application. | |
| 4 | ||
| 5 | ## Getting Started | |
| 6 | ||
| 7 | Import error handling utilities: | |
| 8 | ||
| 9 | ```ts | |
| 10 | import { HttpError } from '@stacksjs/error-handling' | |
| 11 | ``` | |
| 12 | ||
| 13 | ## HTTP Errors | |
| 14 | ||
| 15 | ### Creating HTTP Errors | |
| 16 | ||
| 17 | ```ts | |
| 18 | import { HttpError } from '@stacksjs/error-handling' | |
| 19 | ||
| 20 | // Not Found (404) | |
| 21 | throw new HttpError(404, 'Resource not found') | |
| 22 | ||
| 23 | // Bad Request (400) | |
| 24 | throw new HttpError(400, 'Invalid input data') | |
| 25 | ||
| 26 | // Unauthorized (401) | |
| 27 | throw new HttpError(401, 'Authentication required') | |
| 28 | ||
| 29 | // Forbidden (403) | |
| 30 | throw new HttpError(403, 'You do not have permission to access this resource') | |
| 31 | ||
| 32 | // Internal Server Error (500) | |
| 33 | throw new HttpError(500, 'An unexpected error occurred') | |
| 34 | ``` | |
| 35 | ||
| 36 | ### Custom Error Classes | |
| 37 | ||
| 38 | ```ts | |
| 39 | // errors/ValidationError.ts | |
| 40 | export class ValidationError extends Error { | |
| 41 | public statusCode = 422 | |
| 42 | public errors: Record<string, string[]> | |
| 43 | ||
| 44 | constructor(errors: Record<string, string[]>) { | |
| 45 | super('Validation failed') | |
| 46 | this.name = 'ValidationError' | |
| 47 | this.errors = errors | |
| 48 | } | |
| 49 | ||
| 50 | toJSON() { | |
| 51 | return { | |
| 52 | message: this.message, | |
| 53 | errors: this.errors, | |
| 54 | } | |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | // errors/NotFoundError.ts | |
| 59 | export class NotFoundError extends Error { | |
| 60 | public statusCode = 404 | |
| 61 | public resource: string | |
| 62 | ||
| 63 | constructor(resource: string, id?: string | number) { | |
| 64 | super(id ? `${resource} with ID ${id} not found` : `${resource} not found`) | |
| 65 | this.name = 'NotFoundError' | |
| 66 | this.resource = resource | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | // errors/AuthenticationError.ts | |
| 71 | export class AuthenticationError extends Error { | |
| 72 | public statusCode = 401 | |
| 73 | ||
| 74 | constructor(message = 'Authentication required') { | |
| 75 | super(message) | |
| 76 | this.name = 'AuthenticationError' | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | // errors/AuthorizationError.ts | |
| 81 | export class AuthorizationError extends Error { | |
| 82 | public statusCode = 403 | |
| 83 | ||
| 84 | constructor(message = 'You do not have permission to perform this action') { | |
| 85 | super(message) | |
| 86 | this.name = 'AuthorizationError' | |
| 87 | } | |
| 88 | } | |
| 89 | ``` | |
| 90 | ||
| 91 | ### Using Custom Errors | |
| 92 | ||
| 93 | ```ts | |
| 94 | import { NotFoundError, ValidationError } from '@/errors' | |
| 95 | ||
| 96 | async function getUser(id: number) { | |
| 97 | const user = await User.find(id) | |
| 98 | ||
| 99 | if (!user) { | |
| 100 | throw new NotFoundError('User', id) | |
| 101 | } | |
| 102 | ||
| 103 | return user | |
| 104 | } | |
| 105 | ||
| 106 | async function createUser(data: CreateUserInput) { | |
| 107 | const errors: Record<string, string[]> = {} | |
| 108 | ||
| 109 | if (!data.email) { | |
| 110 | errors.email = ['Email is required'] | |
| 111 | } else if (!isValidEmail(data.email)) { | |
| 112 | errors.email = ['Email format is invalid'] | |
| 113 | } | |
| 114 | ||
| 115 | if (!data.password) { | |
| 116 | errors.password = ['Password is required'] | |
| 117 | } else if (data.password.length < 8) { | |
| 118 | errors.password = ['Password must be at least 8 characters'] | |
| 119 | } | |
| 120 | ||
| 121 | if (Object.keys(errors).length > 0) { | |
| 122 | throw new ValidationError(errors) | |
| 123 | } | |
| 124 | ||
| 125 | return User.create(data) | |
| 126 | } | |
| 127 | ``` | |
| 128 | ||
| 129 | ## Global Error Handler | |
| 130 | ||
| 131 | ### Error Handler Middleware | |
| 132 | ||
| 133 | ```ts | |
| 134 | // middleware/errorHandler.ts | |
| 135 | import { HttpError } from '@stacksjs/error-handling' | |
| 136 | import { ValidationError, NotFoundError, AuthenticationError } from '@/errors' | |
| 137 | ||
| 138 | export async function errorHandler(error: Error, request: Request): Promise<Response> { | |
| 139 | // Log error details | |
| 140 | console.error('Error:', { | |
| 141 | name: error.name, | |
| 142 | message: error.message, | |
| 143 | stack: error.stack, | |
| 144 | url: request.url, | |
| 145 | method: request.method, | |
| 146 | }) | |
| 147 | ||
| 148 | // Handle specific error types | |
| 149 | if (error instanceof ValidationError) { | |
| 150 | return Response.json({ | |
| 151 | error: 'Validation Error', | |
| 152 | message: error.message, | |
| 153 | errors: error.errors, | |
| 154 | }, { status: 422 }) | |
| 155 | } | |
| 156 | ||
| 157 | if (error instanceof NotFoundError) { | |
| 158 | return Response.json({ | |
| 159 | error: 'Not Found', | |
| 160 | message: error.message, | |
| 161 | }, { status: 404 }) | |
| 162 | } | |
| 163 | ||
| 164 | if (error instanceof AuthenticationError) { | |
| 165 | return Response.json({ | |
| 166 | error: 'Unauthorized', | |
| 167 | message: error.message, | |
| 168 | }, { status: 401 }) | |
| 169 | } | |
| 170 | ||
| 171 | if (error instanceof HttpError) { | |
| 172 | return Response.json({ | |
| 173 | error: getStatusText(error.statusCode), | |
| 174 | message: error.message, | |
| 175 | }, { status: error.statusCode }) | |
| 176 | } | |
| 177 | ||
| 178 | // Handle unexpected errors | |
| 179 | const isProduction = process.env.APP_ENV === 'production' | |
| 180 | ||
| 181 | return Response.json({ | |
| 182 | error: 'Internal Server Error', | |
| 183 | message: isProduction ? 'An unexpected error occurred' : error.message, | |
| 184 | ...(isProduction ? {} : { stack: error.stack }), | |
| 185 | }, { status: 500 }) | |
| 186 | } | |
| 187 | ||
| 188 | function getStatusText(status: number): string { | |
| 189 | const statusTexts: Record<number, string> = { | |
| 190 | 400: 'Bad Request', | |
| 191 | 401: 'Unauthorized', | |
| 192 | 403: 'Forbidden', | |
| 193 | 404: 'Not Found', | |
| 194 | 405: 'Method Not Allowed', | |
| 195 | 409: 'Conflict', | |
| 196 | 422: 'Unprocessable Entity', | |
| 197 | 429: 'Too Many Requests', | |
| 198 | 500: 'Internal Server Error', | |
| 199 | 502: 'Bad Gateway', | |
| 200 | 503: 'Service Unavailable', | |
| 201 | } | |
| 202 | return statusTexts[status] || 'Error' | |
| 203 | } | |
| 204 | ``` | |
| 205 | ||
| 206 | ### Wrapping Route Handlers | |
| 207 | ||
| 208 | ```ts | |
| 209 | type RouteHandler = (request: Request) => Promise<Response> | |
| 210 | ||
| 211 | function withErrorHandling(handler: RouteHandler): RouteHandler { | |
| 212 | return async (request: Request) => { | |
| 213 | try { | |
| 214 | return await handler(request) | |
| 215 | } catch (error) { | |
| 216 | return errorHandler(error as Error, request) | |
| 217 | } | |
| 218 | } | |
| 219 | } | |
| 220 | ||
| 221 | // Usage | |
| 222 | router.get('/users/:id', withErrorHandling(async (request) => { | |
| 223 | const { id } = request.params | |
| 224 | const user = await getUser(parseInt(id)) | |
| 225 | return Response.json(user) | |
| 226 | })) | |
| 227 | ``` | |
| 228 | ||
| 229 | ## Try-Catch Patterns | |
| 230 | ||
| 231 | ### Basic Pattern | |
| 232 | ||
| 233 | ```ts | |
| 234 | async function fetchUserOrders(userId: number) { | |
| 235 | try { | |
| 236 | const user = await User.find(userId) | |
| 237 | ||
| 238 | if (!user) { | |
| 239 | throw new NotFoundError('User', userId) | |
| 240 | } | |
| 241 | ||
| 242 | const orders = await Order.where('user_id', '=', userId).get() | |
| 243 | ||
| 244 | return orders | |
| 245 | } catch (error) { | |
| 246 | if (error instanceof NotFoundError) { | |
| 247 | throw error // Re-throw known errors | |
| 248 | } | |
| 249 | ||
| 250 | // Log unexpected errors | |
| 251 | console.error('Failed to fetch user orders:', error) | |
| 252 | throw new HttpError(500, 'Failed to fetch orders') | |
| 253 | } | |
| 254 | } | |
| 255 | ``` | |
| 256 | ||
| 257 | ### With Cleanup | |
| 258 | ||
| 259 | ```ts | |
| 260 | async function processFile(filePath: string) { | |
| 261 | let fileHandle = null | |
| 262 | ||
| 263 | try { | |
| 264 | fileHandle = await Bun.file(filePath).stream() | |
| 265 | // Process file... | |
| 266 | return result | |
| 267 | } catch (error) { | |
| 268 | console.error('File processing failed:', error) | |
| 269 | throw new HttpError(500, 'Failed to process file') | |
| 270 | } finally { | |
| 271 | // Cleanup runs regardless of success/failure | |
| 272 | if (fileHandle) { | |
| 273 | // Close file handle if needed | |
| 274 | } | |
| 275 | } | |
| 276 | } | |
| 277 | ``` | |
| 278 | ||
| 279 | ### Multiple Operations | |
| 280 | ||
| 281 | ```ts | |
| 282 | async function createOrderWithPayment(userId: number, items: CartItem[]) { | |
| 283 | const order = await Order.create({ | |
| 284 | user_id: userId, | |
| 285 | status: 'pending', | |
| 286 | }) | |
| 287 | ||
| 288 | try { | |
| 289 | // Add order items | |
| 290 | await OrderItem.createMany(items.map(item => ({ | |
| 291 | order_id: order.id, | |
| 292 | product_id: item.product_id, | |
| 293 | quantity: item.quantity, | |
| 294 | }))) | |
| 295 | ||
| 296 | // Process payment | |
| 297 | const payment = await processPayment(order) | |
| 298 | ||
| 299 | // Update order status | |
| 300 | await order.update({ status: 'paid', payment_id: payment.id }) | |
| 301 | ||
| 302 | return order | |
| 303 | } catch (error) { | |
| 304 | // Rollback: Delete the order if payment fails | |
| 305 | await order.delete() | |
| 306 | ||
| 307 | if (error instanceof PaymentError) { | |
| 308 | throw new HttpError(402, error.message) | |
| 309 | } | |
| 310 | ||
| 311 | throw error | |
| 312 | } | |
| 313 | } | |
| 314 | ``` | |
| 315 | ||
| 316 | ## Async Error Handling | |
| 317 | ||
| 318 | ### Promise.all with Error Handling | |
| 319 | ||
| 320 | ```ts | |
| 321 | async function fetchAllUserData(userId: number) { | |
| 322 | const [userResult, ordersResult, notificationsResult] = await Promise.allSettled([ | |
| 323 | User.find(userId), | |
| 324 | Order.where('user_id', '=', userId).get(), | |
| 325 | Notification.where('user_id', '=', userId).get(), | |
| 326 | ]) | |
| 327 | ||
| 328 | const errors: string[] = [] | |
| 329 | ||
| 330 | if (userResult.status === 'rejected') { | |
| 331 | errors.push(`Failed to fetch user: ${userResult.reason}`) | |
| 332 | } | |
| 333 | ||
| 334 | if (ordersResult.status === 'rejected') { | |
| 335 | errors.push(`Failed to fetch orders: ${ordersResult.reason}`) | |
| 336 | } | |
| 337 | ||
| 338 | if (notificationsResult.status === 'rejected') { | |
| 339 | errors.push(`Failed to fetch notifications: ${notificationsResult.reason}`) | |
| 340 | } | |
| 341 | ||
| 342 | return { | |
| 343 | user: userResult.status === 'fulfilled' ? userResult.value : null, | |
| 344 | orders: ordersResult.status === 'fulfilled' ? ordersResult.value : [], | |
| 345 | notifications: notificationsResult.status === 'fulfilled' ? notificationsResult.value : [], | |
| 346 | errors: errors.length > 0 ? errors : undefined, | |
| 347 | } | |
| 348 | } | |
| 349 | ``` | |
| 350 | ||
| 351 | ### Retry Pattern | |
| 352 | ||
| 353 | ```ts | |
| 354 | async function withRetry<T>( | |
| 355 | fn: () => Promise<T>, | |
| 356 | options: { | |
| 357 | maxRetries?: number | |
| 358 | delay?: number | |
| 359 | backoff?: number | |
| 360 | } = {} | |
| 361 | ): Promise<T> { | |
| 362 | const { maxRetries = 3, delay = 1000, backoff = 2 } = options | |
| 363 | ||
| 364 | let lastError: Error | |
| 365 | ||
| 366 | for (let attempt = 1; attempt <= maxRetries; attempt++) { | |
| 367 | try { | |
| 368 | return await fn() | |
| 369 | } catch (error) { | |
| 370 | lastError = error as Error | |
| 371 | console.warn(`Attempt ${attempt} failed:`, error) | |
| 372 | ||
| 373 | if (attempt < maxRetries) { | |
| 374 | const waitTime = delay _ Math.pow(backoff, attempt - 1) | |
| 375 | await new Promise(resolve => setTimeout(resolve, waitTime)) | |
| 376 | } | |
| 377 | } | |
| 378 | } | |
| 379 | ||
| 380 | throw lastError! | |
| 381 | } | |
| 382 | ||
| 383 | // Usage | |
| 384 | const result = await withRetry( | |
| 385 | () => fetchExternalAPI(), | |
| 386 | { maxRetries: 3, delay: 1000 } | |
| 387 | ) | |
| 388 | ``` | |
| 389 | ||
| 390 | ## Logging Errors | |
| 391 | ||
| 392 | ### Structured Logging | |
| 393 | ||
| 394 | ```ts | |
| 395 | interface ErrorLog { | |
| 396 | timestamp: string | |
| 397 | level: 'error' | 'warn' | 'info' | |
| 398 | message: string | |
| 399 | error?: { | |
| 400 | name: string | |
| 401 | message: string | |
| 402 | stack?: string | |
| 403 | } | |
| 404 | context?: Record<string, any> | |
| 405 | request?: { | |
| 406 | method: string | |
| 407 | url: string | |
| 408 | headers: Record<string, string> | |
| 409 | } | |
| 410 | } | |
| 411 | ||
| 412 | function logError( | |
| 413 | error: Error, | |
| 414 | context?: Record<string, any>, | |
| 415 | request?: Request | |
| 416 | ): void { | |
| 417 | const log: ErrorLog = { | |
| 418 | timestamp: new Date().toISOString(), | |
| 419 | level: 'error', | |
| 420 | message: error.message, | |
| 421 | error: { | |
| 422 | name: error.name, | |
| 423 | message: error.message, | |
| 424 | stack: error.stack, | |
| 425 | }, | |
| 426 | context, | |
| 427 | } | |
| 428 | ||
| 429 | if (request) { | |
| 430 | log.request = { | |
| 431 | method: request.method, | |
| 432 | url: request.url, | |
| 433 | headers: Object.fromEntries(request.headers.entries()), | |
| 434 | } | |
| 435 | } | |
| 436 | ||
| 437 | console.error(JSON.stringify(log)) | |
| 438 | ||
| 439 | // Send to external service in production | |
| 440 | if (process.env.APP_ENV === 'production') { | |
| 441 | sendToErrorTracking(log) | |
| 442 | } | |
| 443 | } | |
| 444 | ``` | |
| 445 | ||
| 446 | ### Error Tracking Integration | |
| 447 | ||
| 448 | ```ts | |
| 449 | import _ as Sentry from '@sentry/bun' | |
| 450 | ||
| 451 | // Initialize Sentry | |
| 452 | Sentry.init({ | |
| 453 | dsn: process.env.SENTRY_DSN, | |
| 454 | environment: process.env.APP_ENV, | |
| 455 | tracesSampleRate: 1.0, | |
| 456 | }) | |
| 457 | ||
| 458 | function captureError(error: Error, context?: Record<string, any>): void { | |
| 459 | Sentry.captureException(error, { | |
| 460 | extra: context, | |
| 461 | }) | |
| 462 | } | |
| 463 | ||
| 464 | // Usage in error handler | |
| 465 | export async function errorHandler(error: Error, request: Request): Promise<Response> { | |
| 466 | // Capture to Sentry | |
| 467 | captureError(error, { | |
| 468 | url: request.url, | |
| 469 | method: request.method, | |
| 470 | }) | |
| 471 | ||
| 472 | // Continue with normal error handling... | |
| 473 | } | |
| 474 | ``` | |
| 475 | ||
| 476 | ## Debugging | |
| 477 | ||
| 478 | ### Debug Mode | |
| 479 | ||
| 480 | ```ts | |
| 481 | const DEBUG = process.env.APP_DEBUG === 'true' | |
| 482 | ||
| 483 | function debug(...args: any[]): void { | |
| 484 | if (DEBUG) { | |
| 485 | console.log('[DEBUG]', new Date().toISOString(), ...args) | |
| 486 | } | |
| 487 | } | |
| 488 | ||
| 489 | function debugError(error: Error, context?: string): void { | |
| 490 | if (DEBUG) { | |
| 491 | console.error(`[DEBUG ERROR] ${context || 'Error'}:`, { | |
| 492 | name: error.name, | |
| 493 | message: error.message, | |
| 494 | stack: error.stack, | |
| 495 | }) | |
| 496 | } | |
| 497 | } | |
| 498 | ``` | |
| 499 | ||
| 500 | ### Request Debugging | |
| 501 | ||
| 502 | ```ts | |
| 503 | function debugRequest(request: Request): void { | |
| 504 | if (!DEBUG) return | |
| 505 | ||
| 506 | console.log('[DEBUG REQUEST]', { | |
| 507 | method: request.method, | |
| 508 | url: request.url, | |
| 509 | headers: Object.fromEntries(request.headers.entries()), | |
| 510 | }) | |
| 511 | } | |
| 512 | ||
| 513 | function debugResponse(response: Response, duration: number): void { | |
| 514 | if (!DEBUG) return | |
| 515 | ||
| 516 | console.log('[DEBUG RESPONSE]', { | |
| 517 | status: response.status, | |
| 518 | duration: `${duration}ms`, | |
| 519 | headers: Object.fromEntries(response.headers.entries()), | |
| 520 | }) | |
| 521 | } | |
| 522 | ``` | |
| 523 | ||
| 524 | ## API Error Responses | |
| 525 | ||
| 526 | ### Consistent Error Format | |
| 527 | ||
| 528 | ```ts | |
| 529 | interface ApiError { | |
| 530 | error: string | |
| 531 | message: string | |
| 532 | code?: string | |
| 533 | errors?: Record<string, string[]> | |
| 534 | trace_id?: string | |
| 535 | } | |
| 536 | ||
| 537 | function createErrorResponse( | |
| 538 | status: number, | |
| 539 | message: string, | |
| 540 | options?: { | |
| 541 | code?: string | |
| 542 | errors?: Record<string, string[]> | |
| 543 | } | |
| 544 | ): Response { | |
| 545 | const traceId = randomUUIDv7() | |
| 546 | ||
| 547 | const body: ApiError = { | |
| 548 | error: getStatusText(status), | |
| 549 | message, | |
| 550 | trace_id: traceId, | |
| 551 | ...options, | |
| 552 | } | |
| 553 | ||
| 554 | return Response.json(body, { | |
| 555 | status, | |
| 556 | headers: { | |
| 557 | 'X-Trace-ID': traceId, | |
| 558 | }, | |
| 559 | }) | |
| 560 | } | |
| 561 | ||
| 562 | // Usage | |
| 563 | return createErrorResponse(422, 'Validation failed', { | |
| 564 | code: 'VALIDATION_ERROR', | |
| 565 | errors: { | |
| 566 | email: ['Email is required'], | |
| 567 | password: ['Password must be at least 8 characters'], | |
| 568 | }, | |
| 569 | }) | |
| 570 | ``` | |
| 571 | ||
| 572 | ## Best Practices | |
| 573 | ||
| 574 | 1. **Be specific** - Use specific error types for different scenarios | |
| 575 | 2. **Don't swallow errors** - Always log or re-throw errors | |
| 576 | 3. **Provide context** - Include relevant information in error messages | |
| 577 | 4. **Secure in production** - Hide stack traces and internal details | |
| 578 | 5. **Use error boundaries** - Catch errors at appropriate levels | |
| 579 | 6. **Monitor errors** - Use error tracking services in production | |
| 580 | 7. **Test error paths** - Write tests for error scenarios | |
| 581 | ||
| 582 | ```ts | |
| 583 | // Good: Specific error with context | |
| 584 | throw new NotFoundError('User', userId) | |
| 585 | ||
| 586 | // Bad: Generic error without context | |
| 587 | throw new Error('Not found') | |
| 588 | ||
| 589 | // Good: Log and re-throw | |
| 590 | try { | |
| 591 | await processOrder(order) | |
| 592 | } catch (error) { | |
| 593 | console.error('Order processing failed:', { orderId: order.id, error }) | |
| 594 | throw error | |
| 595 | } | |
| 596 | ||
| 597 | // Bad: Swallowing error | |
| 598 | try { | |
| 599 | await processOrder(order) | |
| 600 | } catch (error) { | |
| 601 | // Error is lost! | |
| 602 | } | |
| 603 | ``` | |
| 604 | ||
| 605 | This documentation covers the essential error handling patterns and debugging techniques. Each approach is designed for robust and maintainable error management. | |