also looking at this
Add BunPress guide and pre-E2E quality gates
#4
246 files
+1744
-64381
| @@ -1,366 +0,0 @@ | ||
| 1 | # Error Handling | |
| 2 | ||
| 3 | Stacks provides a comprehensive error handling system built on [ts-error-handling](https://github.com/stacksjs/ts-error-handling), featuring Result types for functional error handling, custom exceptions, and error reporting. | |
| 4 | ||
| 5 | ## Overview | |
| 6 | ||
| 7 | The Stacks error handling system helps you: | |
| 8 | ||
| 9 | - **Handle errors gracefully** - Without crashing your application | |
| 10 | - **Use Result types** - Explicit, type-safe error handling | |
| 11 | - **Create custom exceptions** - Domain-specific error classes | |
| 12 | - **Report errors** - Send errors to monitoring services | |
| 13 | ||
| 14 | ## Quick Start | |
| 15 | ||
| 16 | ### Basic Error Handling | |
| 17 | ||
| 18 | ```typescript | |
| 19 | import { handleError } from '@stacksjs/error-handling' | |
| 20 | ||
| 21 | try { | |
| 22 | await riskyOperation() | |
| 23 | } catch (error) { | |
| 24 | handleError(error) | |
| 25 | } | |
| 26 | ``` | |
| 27 | ||
| 28 | ### With Options | |
| 29 | ||
| 30 | ```typescript | |
| 31 | handleError(error, { | |
| 32 | shouldExit: false, // Don't exit process | |
| 33 | silent: false, // Log to console | |
| 34 | message: 'Custom error context', | |
| 35 | }) | |
| 36 | ``` | |
| 37 | ||
| 38 | ## Result Types | |
| 39 | ||
| 40 | Use Result types for functional error handling, avoiding try-catch blocks. | |
| 41 | ||
| 42 | ### Basic Usage | |
| 43 | ||
| 44 | ```typescript | |
| 45 | import { err, ok, type Result } from '@stacksjs/error-handling' | |
| 46 | ||
| 47 | function divide(a: number, b: number): Result<number, string> { | |
| 48 | if (b === 0) { | |
| 49 | return err('Cannot divide by zero') | |
| 50 | } | |
| 51 | return ok(a / b) | |
| 52 | } | |
| 53 | ||
| 54 | // Usage | |
| 55 | const result = divide(10, 2) | |
| 56 | ||
| 57 | if (result.isOk()) { | |
| 58 | console.log('Result:', result.value) // 5 | |
| 59 | } else { | |
| 60 | console.log('Error:', result.error) | |
| 61 | } | |
| 62 | ``` | |
| 63 | ||
| 64 | ### Async Results | |
| 65 | ||
| 66 | ```typescript | |
| 67 | import { err, ok, type Result } from '@stacksjs/error-handling' | |
| 68 | ||
| 69 | async function fetchUser(id: number): Promise<Result<User, Error>> { | |
| 70 | try { | |
| 71 | const response = await fetch(`/api/users/${id}`) | |
| 72 | if (!response.ok) { | |
| 73 | return err(new Error(`HTTP ${response.status}`)) | |
| 74 | } | |
| 75 | const user = await response.json() | |
| 76 | return ok(user) | |
| 77 | } catch (error) { | |
| 78 | return err(error as Error) | |
| 79 | } | |
| 80 | } | |
| 81 | ||
| 82 | // Usage | |
| 83 | const result = await fetchUser(1) | |
| 84 | if (result.isOk()) { | |
| 85 | console.log('User:', result.value.name) | |
| 86 | } | |
| 87 | ``` | |
| 88 | ||
| 89 | ### Chaining Results | |
| 90 | ||
| 91 | ```typescript | |
| 92 | function validateEmail(email: string): Result<string, string> { | |
| 93 | if (!email.includes('@')) { | |
| 94 | return err('Invalid email format') | |
| 95 | } | |
| 96 | return ok(email.toLowerCase()) | |
| 97 | } | |
| 98 | ||
| 99 | function validatePassword(password: string): Result<string, string> { | |
| 100 | if (password.length < 8) { | |
| 101 | return err('Password must be at least 8 characters') | |
| 102 | } | |
| 103 | return ok(password) | |
| 104 | } | |
| 105 | ||
| 106 | // Chain validations | |
| 107 | const result = validateEmail(email) | |
| 108 | .andThen(() => validatePassword(password)) | |
| 109 | .map(data => ({ ...data, validated: true })) | |
| 110 | ``` | |
| 111 | ||
| 112 | ## Custom Exceptions | |
| 113 | ||
| 114 | ### Creating Custom Exceptions | |
| 115 | ||
| 116 | ```typescript | |
| 117 | // app/Exceptions/ValidationException.ts | |
| 118 | export class ValidationException extends Error { | |
| 119 | public readonly errors: Record<string, string[]> | |
| 120 | ||
| 121 | constructor(errors: Record<string, string[]>) { | |
| 122 | const message = Object.values(errors).flat().join(', ') | |
| 123 | super(message) | |
| 124 | this.name = 'ValidationException' | |
| 125 | this.errors = errors | |
| 126 | } | |
| 127 | ||
| 128 | static fromField(field: string, message: string): ValidationException { | |
| 129 | return new ValidationException({ [field]: [message] }) | |
| 130 | } | |
| 131 | } | |
| 132 | ``` | |
| 133 | ||
| 134 | ### HTTP Exceptions | |
| 135 | ||
| 136 | ```typescript | |
| 137 | // app/Exceptions/HttpException.ts | |
| 138 | export class HttpException extends Error { | |
| 139 | public readonly statusCode: number | |
| 140 | ||
| 141 | constructor(statusCode: number, message: string) { | |
| 142 | super(message) | |
| 143 | this.name = 'HttpException' | |
| 144 | this.statusCode = statusCode | |
| 145 | } | |
| 146 | ||
| 147 | static badRequest(message = 'Bad Request') { | |
| 148 | return new HttpException(400, message) | |
| 149 | } | |
| 150 | ||
| 151 | static unauthorized(message = 'Unauthorized') { | |
| 152 | return new HttpException(401, message) | |
| 153 | } | |
| 154 | ||
| 155 | static notFound(message = 'Not Found') { | |
| 156 | return new HttpException(404, message) | |
| 157 | } | |
| 158 | ||
| 159 | static serverError(message = 'Internal Server Error') { | |
| 160 | return new HttpException(500, message) | |
| 161 | } | |
| 162 | } | |
| 163 | ``` | |
| 164 | ||
| 165 | ### Using Custom Exceptions | |
| 166 | ||
| 167 | ```typescript | |
| 168 | import { ValidationException } from '@/Exceptions/ValidationException' | |
| 169 | import { HttpException } from '@/Exceptions/HttpException' | |
| 170 | ||
| 171 | async function createUser(data: CreateUserInput) { | |
| 172 | // Validation | |
| 173 | const errors: Record<string, string[]> = {} | |
| 174 | ||
| 175 | if (!data.email) { | |
| 176 | errors.email = ['Email is required'] | |
| 177 | } | |
| 178 | if (!data.password || data.password.length < 8) { | |
| 179 | errors.password = ['Password must be at least 8 characters'] | |
| 180 | } | |
| 181 | ||
| 182 | if (Object.keys(errors).length > 0) { | |
| 183 | throw new ValidationException(errors) | |
| 184 | } | |
| 185 | ||
| 186 | // Check for duplicate | |
| 187 | const existing = await User.findByEmail(data.email) | |
| 188 | if (existing) { | |
| 189 | throw HttpException.badRequest('Email already exists') | |
| 190 | } | |
| 191 | ||
| 192 | return User.create(data) | |
| 193 | } | |
| 194 | ``` | |
| 195 | ||
| 196 | ## Error Pages | |
| 197 | ||
| 198 | ### Custom Error Pages | |
| 199 | ||
| 200 | Create custom error pages in `resources/layouts/`: | |
| 201 | ||
| 202 | ```html | |
| 203 | <!-- resources/layouts/404.stx --> | |
| 204 | <template> | |
| 205 | <div class="error-page"> | |
| 206 | <h1>404</h1> | |
| 207 | <h2>Page Not Found</h2> | |
| 208 | <p>The page you're looking for doesn't exist.</p> | |
| 209 | <a href="/">Go back home</a> | |
| 210 | </div> | |
| 211 | </template> | |
| 212 | ``` | |
| 213 | ||
| 214 | ```html | |
| 215 | <!-- resources/layouts/500.stx --> | |
| 216 | <template> | |
| 217 | <div class="error-page"> | |
| 218 | <h1>500</h1> | |
| 219 | <h2>Something went wrong</h2> | |
| 220 | <p>We're sorry, but something went wrong on our end.</p> | |
| 221 | <button onclick="location.reload()">Try Again</button> | |
| 222 | </div> | |
| 223 | </template> | |
| 224 | ``` | |
| 225 | ||
| 226 | ## Global Error Handler | |
| 227 | ||
| 228 | ### HTTP Error Handler | |
| 229 | ||
| 230 | ```typescript | |
| 231 | // app/Middleware/ErrorHandler.ts | |
| 232 | import { HttpException } from '@/Exceptions/HttpException' | |
| 233 | import { ValidationException } from '@/Exceptions/ValidationException' | |
| 234 | import { handleError } from '@stacksjs/error-handling' | |
| 235 | ||
| 236 | export async function errorHandler(error: Error, request: Request) { | |
| 237 | // Log the error | |
| 238 | handleError(error, { shouldExit: false }) | |
| 239 | ||
| 240 | // HTTP exceptions | |
| 241 | if (error instanceof HttpException) { | |
| 242 | return Response.json( | |
| 243 | { error: error.message }, | |
| 244 | { status: error.statusCode } | |
| 245 | ) | |
| 246 | } | |
| 247 | ||
| 248 | // Validation exceptions | |
| 249 | if (error instanceof ValidationException) { | |
| 250 | return Response.json( | |
| 251 | { error: 'Validation failed', errors: error.errors }, | |
| 252 | { status: 422 } | |
| 253 | ) | |
| 254 | } | |
| 255 | ||
| 256 | // Generic server error | |
| 257 | return Response.json( | |
| 258 | { error: 'Internal Server Error' }, | |
| 259 | { status: 500 } | |
| 260 | ) | |
| 261 | } | |
| 262 | ``` | |
| 263 | ||
| 264 | ## Error Reporting | |
| 265 | ||
| 266 | ### Logging Errors | |
| 267 | ||
| 268 | ```typescript | |
| 269 | import { handleError } from '@stacksjs/error-handling' | |
| 270 | import { log } from '@stacksjs/logging' | |
| 271 | ||
| 272 | try { | |
| 273 | await riskyOperation() | |
| 274 | } catch (error) { | |
| 275 | // Log with context | |
| 276 | log.error('Operation failed', { | |
| 277 | error: error.message, | |
| 278 | stack: error.stack, | |
| 279 | userId: currentUser?.id, | |
| 280 | }) | |
| 281 | ||
| 282 | // Handle (may exit process) | |
| 283 | handleError(error, { shouldExit: false }) | |
| 284 | } | |
| 285 | ``` | |
| 286 | ||
| 287 | ### External Error Reporting | |
| 288 | ||
| 289 | ```typescript | |
| 290 | // app/Services/ErrorReporter.ts | |
| 291 | class ErrorReporter { | |
| 292 | static async report(error: Error, context?: Record<string, unknown>) { | |
| 293 | // Send to Sentry, Bugsnag, etc. | |
| 294 | if (process.env.SENTRY_DSN) { | |
| 295 | Sentry.captureException(error, { extra: context }) | |
| 296 | } | |
| 297 | ||
| 298 | // Send to Slack | |
| 299 | if (process.env.SLACK_WEBHOOK_URL) { | |
| 300 | await fetch(process.env.SLACK_WEBHOOK_URL, { | |
| 301 | method: 'POST', | |
| 302 | body: JSON.stringify({ | |
| 303 | text: `Error: ${error.message}`, | |
| 304 | attachments: [{ color: 'danger', text: error.stack }], | |
| 305 | }), | |
| 306 | }) | |
| 307 | } | |
| 308 | } | |
| 309 | } | |
| 310 | ``` | |
| 311 | ||
| 312 | ## Best Practices | |
| 313 | ||
| 314 | ### Use Result Types for Expected Failures | |
| 315 | ||
| 316 | ```typescript | |
| 317 | // Good: Explicit error handling | |
| 318 | async function findUser(id: number): Promise<Result<User, string>> { | |
| 319 | const user = await db.users.find(id) | |
| 320 | if (!user) { | |
| 321 | return err('User not found') | |
| 322 | } | |
| 323 | return ok(user) | |
| 324 | } | |
| 325 | ``` | |
| 326 | ||
| 327 | ### Use Exceptions for Unexpected Failures | |
| 328 | ||
| 329 | ```typescript | |
| 330 | // Good: Exception for unexpected error | |
| 331 | async function processPayment(order: Order) { | |
| 332 | const gateway = getPaymentGateway() | |
| 333 | if (!gateway) { | |
| 334 | throw new Error('Payment gateway not configured') | |
| 335 | } | |
| 336 | return gateway.charge(order) | |
| 337 | } | |
| 338 | ``` | |
| 339 | ||
| 340 | ### Always Add Context | |
| 341 | ||
| 342 | ```typescript | |
| 343 | try { | |
| 344 | await processOrder(orderId) | |
| 345 | } catch (error) { | |
| 346 | handleError(error, { | |
| 347 | message: `Failed to process order ${orderId}`, | |
| 348 | }) | |
| 349 | } | |
| 350 | ``` | |
| 351 | ||
| 352 | ## Related Resources | |
| 353 | ||
| 354 | ### Underlying Libraries | |
| 355 | ||
| 356 | - **[ts-error-handling](https://github.com/stacksjs/ts-error-handling)** - Result types and error utilities | |
| 357 | ||
| 358 | ### Related Stacks Packages | |
| 359 | ||
| 360 | - **[Logging Package](/packages/logging)** - Error logging | |
| 361 | - **[Validation Package](/packages/validation)** - Input validation errors | |
| 362 | ||
| 363 | ### Related Guides | |
| 364 | ||
| 365 | - **[Logging](/basics/logging)** - Logging errors | |
| 366 | - **[Validation](/guide/validation)** - Handling validation errors | |