@geekmidas/errors 0.0.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.
package/src/index.ts ADDED
@@ -0,0 +1,829 @@
1
+ // http-errors.ts - Core HTTP Error Classes and Types
2
+
3
+ /**
4
+ * Base HTTP Error class that extends the native Error.
5
+ * Provides a foundation for all HTTP-specific errors with status codes and structured error responses.
6
+ *
7
+ * @extends Error
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * throw new HttpError(400, 'Bad Request', {
12
+ * details: { field: 'email', message: 'Invalid format' }
13
+ * });
14
+ * ```
15
+ */
16
+ export class HttpError extends Error {
17
+ /** The HTTP status code (e.g., 400, 404, 500) */
18
+ public readonly statusCode: number;
19
+ /** The standard HTTP status message (e.g., 'Bad Request', 'Not Found') */
20
+ public readonly statusMessage: string;
21
+ /** Type discriminator for runtime type checking */
22
+ public readonly isHttpError = true;
23
+ /** Additional error details for debugging or client information */
24
+ public readonly details?: any;
25
+ /** Application-specific error code for client-side handling */
26
+ public readonly code?: string;
27
+
28
+ /**
29
+ * Creates a new HttpError instance.
30
+ *
31
+ * @param statusCode - The HTTP status code
32
+ * @param message - Optional error message for the client
33
+ * @param options - Optional configuration object
34
+ * @param options.statusMessage - Override the default status message
35
+ * @param options.details - Additional error details or context
36
+ * @param options.code - Application-specific error code
37
+ * @param options.cause - The underlying error that caused this error (ES2022)
38
+ */
39
+ constructor(
40
+ statusCode: number,
41
+ message?: string,
42
+ options?: {
43
+ statusMessage?: string;
44
+ details?: any;
45
+ code?: string;
46
+ cause?: Error;
47
+ },
48
+ ) {
49
+ super(message || options?.statusMessage || 'HTTP Error');
50
+ this.name = this.constructor.name;
51
+ this.statusCode = statusCode;
52
+ this.statusMessage =
53
+ options?.statusMessage || this.getDefaultStatusMessage(statusCode);
54
+ this.details = options?.details;
55
+ this.code = options?.code;
56
+
57
+ // Set cause if provided (ES2022 feature)
58
+ if (options?.cause) {
59
+ this.cause = options.cause;
60
+ }
61
+ // @ts-ignore
62
+ // Maintains proper stack trace for where our error was thrown
63
+ Error.captureStackTrace(this, this.constructor);
64
+ }
65
+
66
+ /**
67
+ * Gets the error response body as a JSON string.
68
+ * Used for sending the error response to clients.
69
+ *
70
+ * @returns JSON string containing message, code, and error details
71
+ */
72
+ get body() {
73
+ return JSON.stringify({
74
+ message: this.message,
75
+ code: this.code,
76
+ error: this.details,
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Gets the default HTTP status message for a given status code.
82
+ *
83
+ * @param statusCode - The HTTP status code
84
+ * @returns The standard HTTP status message or 'Unknown Error' if not found
85
+ * @private
86
+ */
87
+ private getDefaultStatusMessage(statusCode: number): string {
88
+ const statusMessages: Record<number, string> = {
89
+ 400: 'Bad Request',
90
+ 401: 'Unauthorized',
91
+ 403: 'Forbidden',
92
+ 404: 'Not Found',
93
+ 405: 'Method Not Allowed',
94
+ 406: 'Not Acceptable',
95
+ 408: 'Request Timeout',
96
+ 409: 'Conflict',
97
+ 410: 'Gone',
98
+ 422: 'Unprocessable Entity',
99
+ 429: 'Too Many Requests',
100
+ 500: 'Internal Server Error',
101
+ 501: 'Not Implemented',
102
+ 502: 'Bad Gateway',
103
+ 503: 'Service Unavailable',
104
+ 504: 'Gateway Timeout',
105
+ };
106
+ return statusMessages[statusCode] || 'Unknown Error';
107
+ }
108
+
109
+ /**
110
+ * Serializes the error to a JSON-compatible object.
111
+ * Useful for logging and debugging purposes.
112
+ *
113
+ * @returns Object representation of the error including stack trace
114
+ */
115
+ toJSON() {
116
+ return {
117
+ name: this.name,
118
+ message: this.message,
119
+ statusCode: this.statusCode,
120
+ statusMessage: this.statusMessage,
121
+ code: this.code,
122
+ details: this.details,
123
+ stack: this.stack,
124
+ };
125
+ }
126
+ }
127
+
128
+ // Client Error Classes (4xx)
129
+
130
+ /**
131
+ * Represents a 400 Bad Request error.
132
+ * Used when the client sends a malformed or invalid request.
133
+ *
134
+ * @extends HttpError
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * throw new BadRequestError('Invalid JSON', { line: 5, column: 12 });
139
+ * ```
140
+ */
141
+ export class BadRequestError extends HttpError {
142
+ constructor(message?: string, details?: any) {
143
+ super(400, message, { details });
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Represents a 401 Unauthorized error.
149
+ * Used when authentication is required but not provided or invalid.
150
+ *
151
+ * @extends HttpError
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * throw new UnauthorizedError('Invalid token');
156
+ * ```
157
+ */
158
+ export class UnauthorizedError extends HttpError {
159
+ constructor(message?: string, details?: any) {
160
+ super(401, message, { details });
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Represents a 403 Forbidden error.
166
+ * Used when the client is authenticated but lacks permission for the resource.
167
+ *
168
+ * @extends HttpError
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * throw new ForbiddenError('Insufficient permissions', { required: 'admin' });
173
+ * ```
174
+ */
175
+ export class ForbiddenError extends HttpError {
176
+ constructor(message?: string, details?: any) {
177
+ super(403, message, { details });
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Represents a 404 Not Found error.
183
+ * Used when the requested resource doesn't exist.
184
+ *
185
+ * @extends HttpError
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * throw new NotFoundError('User not found', { userId: '123' });
190
+ * ```
191
+ */
192
+ export class NotFoundError extends HttpError {
193
+ constructor(message?: string, details?: any) {
194
+ super(404, message, { details });
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Represents a 405 Method Not Allowed error.
200
+ * Used when the HTTP method is not supported for the requested resource.
201
+ *
202
+ * @extends HttpError
203
+ *
204
+ * @example
205
+ * ```typescript
206
+ * throw new MethodNotAllowedError('DELETE not supported', ['GET', 'POST', 'PUT']);
207
+ * ```
208
+ */
209
+ export class MethodNotAllowedError extends HttpError {
210
+ /**
211
+ * @param message - Optional error message
212
+ * @param allowedMethods - Array of allowed HTTP methods for this resource
213
+ */
214
+ constructor(message?: string, allowedMethods?: string[]) {
215
+ super(405, message, {
216
+ details: allowedMethods ? { allowedMethods } : undefined,
217
+ });
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Represents a 409 Conflict error.
223
+ * Used when the request conflicts with the current state of the resource.
224
+ *
225
+ * @extends HttpError
226
+ *
227
+ * @example
228
+ * ```typescript
229
+ * throw new ConflictError('Email already exists', { email: 'user@example.com' });
230
+ * ```
231
+ */
232
+ export class ConflictError extends HttpError {
233
+ constructor(message?: string, details?: any) {
234
+ super(409, message, { details });
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Represents a 422 Unprocessable Entity error.
240
+ * Used when the request is well-formed but contains semantic errors.
241
+ *
242
+ * @extends HttpError
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * throw new UnprocessableEntityError('Validation failed', {
247
+ * email: 'Invalid format',
248
+ * age: 'Must be 18 or older'
249
+ * });
250
+ * ```
251
+ */
252
+ export class UnprocessableEntityError extends HttpError {
253
+ /**
254
+ * @param message - Optional error message
255
+ * @param validationErrors - Object containing field-specific validation errors
256
+ */
257
+ constructor(message?: string, validationErrors?: any) {
258
+ super(422, message, {
259
+ details: validationErrors ? { validationErrors } : undefined,
260
+ });
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Represents a 429 Too Many Requests error.
266
+ * Used when the client has exceeded rate limits.
267
+ *
268
+ * @extends HttpError
269
+ *
270
+ * @example
271
+ * ```typescript
272
+ * throw new TooManyRequestsError('Rate limit exceeded', 60); // retry after 60 seconds
273
+ * ```
274
+ */
275
+ export class TooManyRequestsError extends HttpError {
276
+ /**
277
+ * @param message - Optional error message
278
+ * @param retryAfter - Number of seconds the client should wait before retrying
279
+ */
280
+ constructor(message?: string, retryAfter?: number) {
281
+ super(429, message, {
282
+ details: retryAfter ? { retryAfter } : undefined,
283
+ });
284
+ }
285
+ }
286
+
287
+ // Server Error Classes (5xx)
288
+
289
+ /**
290
+ * Represents a 500 Internal Server Error.
291
+ * Used for unexpected server-side errors.
292
+ *
293
+ * @extends HttpError
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * throw new InternalServerError('Database connection failed');
298
+ * ```
299
+ */
300
+ export class InternalServerError extends HttpError {
301
+ constructor(message?: string, details?: any) {
302
+ super(500, message, { details });
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Represents a 501 Not Implemented error.
308
+ * Used when the server doesn't support the requested functionality.
309
+ *
310
+ * @extends HttpError
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * throw new NotImplementedError('WebSocket support not implemented');
315
+ * ```
316
+ */
317
+ export class NotImplementedError extends HttpError {
318
+ constructor(message?: string, details?: any) {
319
+ super(501, message, { details });
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Represents a 502 Bad Gateway error.
325
+ * Used when the server receives an invalid response from an upstream server.
326
+ *
327
+ * @extends HttpError
328
+ *
329
+ * @example
330
+ * ```typescript
331
+ * throw new BadGatewayError('Upstream server error');
332
+ * ```
333
+ */
334
+ export class BadGatewayError extends HttpError {
335
+ constructor(message?: string, details?: any) {
336
+ super(502, message, { details });
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Represents a 503 Service Unavailable error.
342
+ * Used when the server is temporarily unable to handle requests.
343
+ *
344
+ * @extends HttpError
345
+ *
346
+ * @example
347
+ * ```typescript
348
+ * throw new ServiceUnavailableError('Maintenance in progress', 300); // retry after 5 minutes
349
+ * ```
350
+ */
351
+ export class ServiceUnavailableError extends HttpError {
352
+ /**
353
+ * @param message - Optional error message
354
+ * @param retryAfter - Number of seconds the client should wait before retrying
355
+ */
356
+ constructor(message?: string, retryAfter?: number) {
357
+ super(503, message, {
358
+ details: retryAfter ? { retryAfter } : undefined,
359
+ });
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Represents a 504 Gateway Timeout error.
365
+ * Used when the server doesn't receive a timely response from an upstream server.
366
+ *
367
+ * @extends HttpError
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * throw new GatewayTimeoutError('Upstream server timeout');
372
+ * ```
373
+ */
374
+ export class GatewayTimeoutError extends HttpError {
375
+ constructor(message?: string, details?: any) {
376
+ super(504, message, { details });
377
+ }
378
+ }
379
+
380
+ // Type definitions for different error factory signatures
381
+
382
+ /** Factory function for standard HTTP errors with optional details */
383
+ type StandardErrorFactory = (message?: string, details?: any) => HttpError;
384
+ /** Factory function for Method Not Allowed errors with allowed methods */
385
+ type MethodNotAllowedFactory = (
386
+ message?: string,
387
+ allowedMethods?: string[],
388
+ ) => MethodNotAllowedError;
389
+ /** Factory function for errors that include retry-after information */
390
+ type RetryAfterFactory = (message?: string, retryAfter?: number) => HttpError;
391
+ /** Factory function for validation errors with field-specific errors */
392
+ type ValidationErrorFactory = (
393
+ message?: string,
394
+ validationErrors?: any,
395
+ ) => UnprocessableEntityError;
396
+
397
+ /** Discriminated union for all factory types */
398
+ type ErrorFactory =
399
+ | { type: 'standard'; factory: StandardErrorFactory }
400
+ | { type: 'methodNotAllowed'; factory: MethodNotAllowedFactory }
401
+ | { type: 'retryAfter'; factory: RetryAfterFactory }
402
+ | { type: 'validation'; factory: ValidationErrorFactory };
403
+
404
+ /** Type-safe error registry mapping status codes to their factory functions */
405
+ const errorRegistry = {
406
+ 400: {
407
+ type: 'standard',
408
+ factory: (m: string, d: any) => new BadRequestError(m, d),
409
+ },
410
+ 401: {
411
+ type: 'standard',
412
+ factory: (m: string, d: any) => new UnauthorizedError(m, d),
413
+ },
414
+ 403: {
415
+ type: 'standard',
416
+ factory: (m: string, d: any) => new ForbiddenError(m, d),
417
+ },
418
+ 404: {
419
+ type: 'standard',
420
+ factory: (m: string, d: any) => new NotFoundError(m, d),
421
+ },
422
+ 405: {
423
+ type: 'methodNotAllowed',
424
+ factory: (m: string, am: string[]) => new MethodNotAllowedError(m, am),
425
+ },
426
+ 409: {
427
+ type: 'standard',
428
+ factory: (m: string, d: any) => new ConflictError(m, d),
429
+ },
430
+ 422: {
431
+ type: 'validation',
432
+ factory: (m: string, ve: any) => new UnprocessableEntityError(m, ve),
433
+ },
434
+ 429: {
435
+ type: 'retryAfter',
436
+ factory: (m: string, ra: number) => new TooManyRequestsError(m, ra),
437
+ },
438
+ 500: {
439
+ type: 'standard',
440
+ factory: (m: string, d: any) => new InternalServerError(m, d),
441
+ },
442
+ 501: {
443
+ type: 'standard',
444
+ factory: (m: string, d: any) => new NotImplementedError(m, d),
445
+ },
446
+ 502: {
447
+ type: 'standard',
448
+ factory: (m: string, d: any) => new BadGatewayError(m, d),
449
+ },
450
+ 503: {
451
+ type: 'retryAfter',
452
+ factory: (m: string, ra: number) => new ServiceUnavailableError(m, ra),
453
+ },
454
+ 504: {
455
+ type: 'standard',
456
+ factory: (m: string, d: any) => new GatewayTimeoutError(m, d),
457
+ },
458
+ } as const;
459
+
460
+ /** Valid status codes that have registered error factories */
461
+ type ValidStatusCode = keyof typeof errorRegistry;
462
+
463
+ /** Type-safe options based on status code, ensuring correct parameters for each error type */
464
+ type ErrorOptions<T extends number> = T extends 405
465
+ ? { allowedMethods?: string[]; code?: string; cause?: Error }
466
+ : T extends 422
467
+ ? { validationErrors?: any; code?: string; cause?: Error }
468
+ : T extends 429 | 503
469
+ ? { retryAfter?: number; code?: string; cause?: Error }
470
+ : { details?: any; code?: string; cause?: Error };
471
+
472
+ /** Handler functions for each factory type */
473
+ const factoryHandlers: Record<
474
+ ErrorFactory['type'],
475
+ (entry: any, message?: string, options?: any) => HttpError
476
+ > = {
477
+ standard: (entry, message, options) =>
478
+ entry.factory(message, options?.details),
479
+ methodNotAllowed: (entry, message, options) =>
480
+ entry.factory(message, options?.allowedMethods),
481
+ retryAfter: (entry, message, options) =>
482
+ entry.factory(message, options?.retryAfter),
483
+ validation: (entry, message, options) =>
484
+ entry.factory(message, options?.validationErrors),
485
+ };
486
+
487
+ /**
488
+ * Creates an HTTP error with type-safe options based on the status code.
489
+ * Provides IntelliSense support for status-code-specific options.
490
+ *
491
+ * @overload For known status codes with specific options
492
+ * @param statusCode - A valid HTTP status code from the registry
493
+ * @param message - Optional error message
494
+ * @param options - Status-code-specific options
495
+ * @returns The appropriate HttpError subclass
496
+ *
497
+ * @example
498
+ * ```typescript
499
+ * // TypeScript knows allowedMethods is valid for 405
500
+ * createHttpError(405, 'Method not allowed', { allowedMethods: ['GET', 'POST'] });
501
+ *
502
+ * // TypeScript knows retryAfter is valid for 429
503
+ * createHttpError(429, 'Rate limited', { retryAfter: 60 });
504
+ * ```
505
+ */
506
+ export function createHttpError<T extends ValidStatusCode>(
507
+ statusCode: T,
508
+ message?: string,
509
+ options?: ErrorOptions<T>,
510
+ ): HttpError;
511
+ export function createHttpError(
512
+ statusCode: number,
513
+ message?: string,
514
+ options?: HttpErrorOptions,
515
+ ): HttpError;
516
+ export function createHttpError(
517
+ statusCode: number,
518
+ message?: string,
519
+ options?: any,
520
+ ): HttpError {
521
+ const entry = errorRegistry[statusCode as ValidStatusCode];
522
+
523
+ if (entry) {
524
+ const handler = factoryHandlers[entry.type];
525
+ return handler(entry, message, options);
526
+ }
527
+
528
+ // Fallback to generic HttpError for unknown status codes
529
+ return new HttpError(statusCode, message, options);
530
+ }
531
+
532
+ /**
533
+ * Type-safe error creation utilities with descriptive method names.
534
+ * Provides a fluent API for creating specific HTTP errors.
535
+ *
536
+ * @example
537
+ * ```typescript
538
+ * createError.notFound('User not found');
539
+ * createError.badRequest('Invalid input', { field: 'email' });
540
+ * createError.methodNotAllowed('DELETE not supported', ['GET', 'POST']);
541
+ * ```
542
+ */
543
+ export const createError = {
544
+ badRequest: (message?: string, details?: any) =>
545
+ new BadRequestError(message, details),
546
+
547
+ unauthorized: (message?: string, details?: any) =>
548
+ new UnauthorizedError(message, details),
549
+
550
+ forbidden: (message?: string, details?: any) =>
551
+ new ForbiddenError(message, details),
552
+
553
+ notFound: (message?: string, details?: any) =>
554
+ new NotFoundError(message, details),
555
+
556
+ methodNotAllowed: (message?: string, allowedMethods?: string[]) =>
557
+ new MethodNotAllowedError(message, allowedMethods),
558
+
559
+ conflict: (message?: string, details?: any) =>
560
+ new ConflictError(message, details),
561
+
562
+ unprocessableEntity: (message?: string, validationErrors?: any) =>
563
+ new UnprocessableEntityError(message, validationErrors),
564
+
565
+ tooManyRequests: (message?: string, retryAfter?: number) =>
566
+ new TooManyRequestsError(message, retryAfter),
567
+
568
+ internalServerError: (message?: string, details?: any) =>
569
+ new InternalServerError(message, details),
570
+
571
+ notImplemented: (message?: string, details?: any) =>
572
+ new NotImplementedError(message, details),
573
+
574
+ badGateway: (message?: string, details?: any) =>
575
+ new BadGatewayError(message, details),
576
+
577
+ serviceUnavailable: (message?: string, retryAfter?: number) =>
578
+ new ServiceUnavailableError(message, retryAfter),
579
+
580
+ gatewayTimeout: (message?: string, details?: any) =>
581
+ new GatewayTimeoutError(message, details),
582
+ } as const;
583
+
584
+ // Type guards
585
+
586
+ /**
587
+ * Type guard to check if an error is an HttpError.
588
+ * Works with both instanceof checks and duck typing.
589
+ *
590
+ * @param error - The error to check
591
+ * @returns True if the error is an HttpError
592
+ *
593
+ * @example
594
+ * ```typescript
595
+ * try {
596
+ * // some code
597
+ * } catch (error) {
598
+ * if (isHttpError(error)) {
599
+ * console.log(`HTTP ${error.statusCode}: ${error.message}`);
600
+ * }
601
+ * }
602
+ * ```
603
+ */
604
+ export function isHttpError(error: unknown): error is HttpError {
605
+ return (
606
+ error instanceof HttpError ||
607
+ (error !== null &&
608
+ typeof error === 'object' &&
609
+ 'isHttpError' in error &&
610
+ error.isHttpError === true)
611
+ );
612
+ }
613
+
614
+ /**
615
+ * Type guard to check if an error is a client error (4xx status code).
616
+ *
617
+ * @param error - The error to check
618
+ * @returns True if the error is an HttpError with a 4xx status code
619
+ *
620
+ * @example
621
+ * ```typescript
622
+ * if (isClientError(error)) {
623
+ * // Log client error metrics
624
+ * }
625
+ * ```
626
+ */
627
+ export function isClientError(error: unknown): error is HttpError {
628
+ return (
629
+ isHttpError(error) && error.statusCode >= 400 && error.statusCode < 500
630
+ );
631
+ }
632
+
633
+ /**
634
+ * Type guard to check if an error is a server error (5xx status code).
635
+ *
636
+ * @param error - The error to check
637
+ * @returns True if the error is an HttpError with a 5xx status code
638
+ *
639
+ * @example
640
+ * ```typescript
641
+ * if (isServerError(error)) {
642
+ * // Trigger alerts for server errors
643
+ * }
644
+ * ```
645
+ */
646
+ export function isServerError(error: unknown): error is HttpError {
647
+ return (
648
+ isHttpError(error) && error.statusCode >= 500 && error.statusCode < 600
649
+ );
650
+ }
651
+
652
+ // Utility functions
653
+
654
+ /**
655
+ * Wraps an unknown error into an HttpError.
656
+ * If the error is already an HttpError, returns it unchanged.
657
+ *
658
+ * @param error - The error to wrap
659
+ * @param statusCode - The HTTP status code to use (defaults to 500)
660
+ * @param message - Optional message to override the original error message
661
+ * @returns An HttpError instance
662
+ *
663
+ * @example
664
+ * ```typescript
665
+ * try {
666
+ * await someOperation();
667
+ * } catch (error) {
668
+ * throw wrapError(error, 503, 'Service temporarily unavailable');
669
+ * }
670
+ * ```
671
+ */
672
+ export function wrapError(
673
+ error: unknown,
674
+ statusCode = 500,
675
+ message?: string,
676
+ ): HttpError {
677
+ if (isHttpError(error)) {
678
+ return error;
679
+ }
680
+
681
+ if (error instanceof HttpError) {
682
+ return error;
683
+ }
684
+
685
+ return new HttpError(statusCode, message || 'An unknown error occurred', {
686
+ details: { originalError: error },
687
+ });
688
+ }
689
+
690
+ // Types for better TypeScript support
691
+
692
+ /**
693
+ * Options for creating an HttpError.
694
+ */
695
+ export interface HttpErrorOptions {
696
+ statusMessage?: string;
697
+ details?: any;
698
+ code?: string;
699
+ cause?: Error;
700
+ }
701
+
702
+ /**
703
+ * Constructor type for HttpError classes.
704
+ * Useful for factory patterns and dependency injection.
705
+ */
706
+ export type HttpErrorConstructor = new (
707
+ message?: string,
708
+ options?: HttpErrorOptions,
709
+ ) => HttpError;
710
+
711
+ /**
712
+ * HTTP status code enum for type-safe status code usage.
713
+ * Includes common 2xx, 3xx, 4xx, and 5xx status codes.
714
+ */
715
+ export enum HttpStatusCode {
716
+ // 2xx Success
717
+ OK = 200,
718
+ CREATED = 201,
719
+ ACCEPTED = 202,
720
+ NO_CONTENT = 204,
721
+
722
+ // 3xx Redirection
723
+ MOVED_PERMANENTLY = 301,
724
+ FOUND = 302,
725
+ NOT_MODIFIED = 304,
726
+
727
+ // 4xx Client Error
728
+ BAD_REQUEST = 400,
729
+ UNAUTHORIZED = 401,
730
+ FORBIDDEN = 403,
731
+ NOT_FOUND = 404,
732
+ METHOD_NOT_ALLOWED = 405,
733
+ NOT_ACCEPTABLE = 406,
734
+ REQUEST_TIMEOUT = 408,
735
+ CONFLICT = 409,
736
+ GONE = 410,
737
+ UNPROCESSABLE_ENTITY = 422,
738
+ TOO_MANY_REQUESTS = 429,
739
+
740
+ // 5xx Server Error
741
+ INTERNAL_SERVER_ERROR = 500,
742
+ NOT_IMPLEMENTED = 501,
743
+ BAD_GATEWAY = 502,
744
+ SERVICE_UNAVAILABLE = 503,
745
+ GATEWAY_TIMEOUT = 504,
746
+ }
747
+
748
+ /**
749
+ * Namespace containing all HTTP error classes.
750
+ * Useful for importing all error types at once.
751
+ *
752
+ * @example
753
+ * ```typescript
754
+ * import { HttpErrors } from '@geekmidas/errors';
755
+ * throw new HttpErrors.NotFoundError('Resource not found');
756
+ * ```
757
+ */
758
+ export const HttpErrors = {
759
+ HttpError,
760
+ BadRequestError,
761
+ UnauthorizedError,
762
+ ForbiddenError,
763
+ NotFoundError,
764
+ MethodNotAllowedError,
765
+ ConflictError,
766
+ UnprocessableEntityError,
767
+ TooManyRequestsError,
768
+ InternalServerError,
769
+ NotImplementedError,
770
+ BadGatewayError,
771
+ ServiceUnavailableError,
772
+ GatewayTimeoutError,
773
+ };
774
+
775
+ // Usage examples:
776
+ /*
777
+ // Basic usage
778
+ throw new NotFoundError('User not found');
779
+ throw new BadRequestError('Invalid email format', { field: 'email' });
780
+
781
+ // With validation errors
782
+ throw new UnprocessableEntityError('Validation failed', {
783
+ email: 'Invalid email format',
784
+ password: 'Password must be at least 8 characters',
785
+ });
786
+
787
+ // Type-safe factory function with IntelliSense support
788
+ throw createHttpError(405, 'Method not allowed', {
789
+ allowedMethods: ['GET', 'POST'] // TypeScript knows this is the correct option!
790
+ });
791
+
792
+ throw createHttpError(429, 'Too many requests', {
793
+ retryAfter: 60 // TypeScript knows this needs retryAfter, not details!
794
+ });
795
+
796
+ throw createHttpError(422, 'Validation failed', {
797
+ validationErrors: { // TypeScript knows this is for validation errors
798
+ email: 'Invalid format',
799
+ age: 'Must be 18+'
800
+ }
801
+ });
802
+
803
+ // Using the type-safe createError object
804
+ throw createError.methodNotAllowed('DELETE not supported', ['GET', 'POST']);
805
+ throw createError.tooManyRequests('Rate limit exceeded', 60);
806
+ throw createError.unprocessableEntity('Invalid input', {
807
+ field: 'email',
808
+ message: 'Invalid format'
809
+ });
810
+
811
+ // TypeScript will show errors for incorrect usage:
812
+ // throw createHttpError(404, 'Not found', { retryAfter: 60 }); // ❌ Type error!
813
+ // throw createError.notFound('User not found', 60); // ❌ Type error!
814
+
815
+ // Wrapping unknown errors
816
+ try {
817
+ await someAsyncOperation();
818
+ } catch (error) {
819
+ throw wrapError(error, 500, 'Failed to process request');
820
+ }
821
+
822
+ // In Express middleware
823
+ app.use(expressErrorHandler);
824
+
825
+ // Type checking
826
+ if (isClientError(error)) {
827
+ console.log('Client made a bad request');
828
+ }
829
+ */