@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.
@@ -0,0 +1,534 @@
1
+ //#region src/index.d.ts
2
+ /**
3
+ * Base HTTP Error class that extends the native Error.
4
+ * Provides a foundation for all HTTP-specific errors with status codes and structured error responses.
5
+ *
6
+ * @extends Error
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * throw new HttpError(400, 'Bad Request', {
11
+ * details: { field: 'email', message: 'Invalid format' }
12
+ * });
13
+ * ```
14
+ */
15
+ declare class HttpError extends Error {
16
+ /** The HTTP status code (e.g., 400, 404, 500) */
17
+ readonly statusCode: number;
18
+ /** The standard HTTP status message (e.g., 'Bad Request', 'Not Found') */
19
+ readonly statusMessage: string;
20
+ /** Type discriminator for runtime type checking */
21
+ readonly isHttpError = true;
22
+ /** Additional error details for debugging or client information */
23
+ readonly details?: any;
24
+ /** Application-specific error code for client-side handling */
25
+ readonly code?: string;
26
+ /**
27
+ * Creates a new HttpError instance.
28
+ *
29
+ * @param statusCode - The HTTP status code
30
+ * @param message - Optional error message for the client
31
+ * @param options - Optional configuration object
32
+ * @param options.statusMessage - Override the default status message
33
+ * @param options.details - Additional error details or context
34
+ * @param options.code - Application-specific error code
35
+ * @param options.cause - The underlying error that caused this error (ES2022)
36
+ */
37
+ constructor(statusCode: number, message?: string, options?: {
38
+ statusMessage?: string;
39
+ details?: any;
40
+ code?: string;
41
+ cause?: Error;
42
+ });
43
+ /**
44
+ * Gets the error response body as a JSON string.
45
+ * Used for sending the error response to clients.
46
+ *
47
+ * @returns JSON string containing message, code, and error details
48
+ */
49
+ get body(): string;
50
+ /**
51
+ * Gets the default HTTP status message for a given status code.
52
+ *
53
+ * @param statusCode - The HTTP status code
54
+ * @returns The standard HTTP status message or 'Unknown Error' if not found
55
+ * @private
56
+ */
57
+ private getDefaultStatusMessage;
58
+ /**
59
+ * Serializes the error to a JSON-compatible object.
60
+ * Useful for logging and debugging purposes.
61
+ *
62
+ * @returns Object representation of the error including stack trace
63
+ */
64
+ toJSON(): {
65
+ name: string;
66
+ message: string;
67
+ statusCode: number;
68
+ statusMessage: string;
69
+ code: string | undefined;
70
+ details: any;
71
+ stack: string | undefined;
72
+ };
73
+ }
74
+ /**
75
+ * Represents a 400 Bad Request error.
76
+ * Used when the client sends a malformed or invalid request.
77
+ *
78
+ * @extends HttpError
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * throw new BadRequestError('Invalid JSON', { line: 5, column: 12 });
83
+ * ```
84
+ */
85
+ declare class BadRequestError extends HttpError {
86
+ constructor(message?: string, details?: any);
87
+ }
88
+ /**
89
+ * Represents a 401 Unauthorized error.
90
+ * Used when authentication is required but not provided or invalid.
91
+ *
92
+ * @extends HttpError
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * throw new UnauthorizedError('Invalid token');
97
+ * ```
98
+ */
99
+ declare class UnauthorizedError extends HttpError {
100
+ constructor(message?: string, details?: any);
101
+ }
102
+ /**
103
+ * Represents a 403 Forbidden error.
104
+ * Used when the client is authenticated but lacks permission for the resource.
105
+ *
106
+ * @extends HttpError
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * throw new ForbiddenError('Insufficient permissions', { required: 'admin' });
111
+ * ```
112
+ */
113
+ declare class ForbiddenError extends HttpError {
114
+ constructor(message?: string, details?: any);
115
+ }
116
+ /**
117
+ * Represents a 404 Not Found error.
118
+ * Used when the requested resource doesn't exist.
119
+ *
120
+ * @extends HttpError
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * throw new NotFoundError('User not found', { userId: '123' });
125
+ * ```
126
+ */
127
+ declare class NotFoundError extends HttpError {
128
+ constructor(message?: string, details?: any);
129
+ }
130
+ /**
131
+ * Represents a 405 Method Not Allowed error.
132
+ * Used when the HTTP method is not supported for the requested resource.
133
+ *
134
+ * @extends HttpError
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * throw new MethodNotAllowedError('DELETE not supported', ['GET', 'POST', 'PUT']);
139
+ * ```
140
+ */
141
+ declare class MethodNotAllowedError extends HttpError {
142
+ /**
143
+ * @param message - Optional error message
144
+ * @param allowedMethods - Array of allowed HTTP methods for this resource
145
+ */
146
+ constructor(message?: string, allowedMethods?: string[]);
147
+ }
148
+ /**
149
+ * Represents a 409 Conflict error.
150
+ * Used when the request conflicts with the current state of the resource.
151
+ *
152
+ * @extends HttpError
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * throw new ConflictError('Email already exists', { email: 'user@example.com' });
157
+ * ```
158
+ */
159
+ declare class ConflictError extends HttpError {
160
+ constructor(message?: string, details?: any);
161
+ }
162
+ /**
163
+ * Represents a 422 Unprocessable Entity error.
164
+ * Used when the request is well-formed but contains semantic errors.
165
+ *
166
+ * @extends HttpError
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * throw new UnprocessableEntityError('Validation failed', {
171
+ * email: 'Invalid format',
172
+ * age: 'Must be 18 or older'
173
+ * });
174
+ * ```
175
+ */
176
+ declare class UnprocessableEntityError extends HttpError {
177
+ /**
178
+ * @param message - Optional error message
179
+ * @param validationErrors - Object containing field-specific validation errors
180
+ */
181
+ constructor(message?: string, validationErrors?: any);
182
+ }
183
+ /**
184
+ * Represents a 429 Too Many Requests error.
185
+ * Used when the client has exceeded rate limits.
186
+ *
187
+ * @extends HttpError
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * throw new TooManyRequestsError('Rate limit exceeded', 60); // retry after 60 seconds
192
+ * ```
193
+ */
194
+ declare class TooManyRequestsError extends HttpError {
195
+ /**
196
+ * @param message - Optional error message
197
+ * @param retryAfter - Number of seconds the client should wait before retrying
198
+ */
199
+ constructor(message?: string, retryAfter?: number);
200
+ }
201
+ /**
202
+ * Represents a 500 Internal Server Error.
203
+ * Used for unexpected server-side errors.
204
+ *
205
+ * @extends HttpError
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * throw new InternalServerError('Database connection failed');
210
+ * ```
211
+ */
212
+ declare class InternalServerError extends HttpError {
213
+ constructor(message?: string, details?: any);
214
+ }
215
+ /**
216
+ * Represents a 501 Not Implemented error.
217
+ * Used when the server doesn't support the requested functionality.
218
+ *
219
+ * @extends HttpError
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * throw new NotImplementedError('WebSocket support not implemented');
224
+ * ```
225
+ */
226
+ declare class NotImplementedError extends HttpError {
227
+ constructor(message?: string, details?: any);
228
+ }
229
+ /**
230
+ * Represents a 502 Bad Gateway error.
231
+ * Used when the server receives an invalid response from an upstream server.
232
+ *
233
+ * @extends HttpError
234
+ *
235
+ * @example
236
+ * ```typescript
237
+ * throw new BadGatewayError('Upstream server error');
238
+ * ```
239
+ */
240
+ declare class BadGatewayError extends HttpError {
241
+ constructor(message?: string, details?: any);
242
+ }
243
+ /**
244
+ * Represents a 503 Service Unavailable error.
245
+ * Used when the server is temporarily unable to handle requests.
246
+ *
247
+ * @extends HttpError
248
+ *
249
+ * @example
250
+ * ```typescript
251
+ * throw new ServiceUnavailableError('Maintenance in progress', 300); // retry after 5 minutes
252
+ * ```
253
+ */
254
+ declare class ServiceUnavailableError extends HttpError {
255
+ /**
256
+ * @param message - Optional error message
257
+ * @param retryAfter - Number of seconds the client should wait before retrying
258
+ */
259
+ constructor(message?: string, retryAfter?: number);
260
+ }
261
+ /**
262
+ * Represents a 504 Gateway Timeout error.
263
+ * Used when the server doesn't receive a timely response from an upstream server.
264
+ *
265
+ * @extends HttpError
266
+ *
267
+ * @example
268
+ * ```typescript
269
+ * throw new GatewayTimeoutError('Upstream server timeout');
270
+ * ```
271
+ */
272
+ declare class GatewayTimeoutError extends HttpError {
273
+ constructor(message?: string, details?: any);
274
+ }
275
+ /** Type-safe error registry mapping status codes to their factory functions */
276
+ declare const errorRegistry: {
277
+ readonly 400: {
278
+ readonly type: "standard";
279
+ readonly factory: (m: string, d: any) => BadRequestError;
280
+ };
281
+ readonly 401: {
282
+ readonly type: "standard";
283
+ readonly factory: (m: string, d: any) => UnauthorizedError;
284
+ };
285
+ readonly 403: {
286
+ readonly type: "standard";
287
+ readonly factory: (m: string, d: any) => ForbiddenError;
288
+ };
289
+ readonly 404: {
290
+ readonly type: "standard";
291
+ readonly factory: (m: string, d: any) => NotFoundError;
292
+ };
293
+ readonly 405: {
294
+ readonly type: "methodNotAllowed";
295
+ readonly factory: (m: string, am: string[]) => MethodNotAllowedError;
296
+ };
297
+ readonly 409: {
298
+ readonly type: "standard";
299
+ readonly factory: (m: string, d: any) => ConflictError;
300
+ };
301
+ readonly 422: {
302
+ readonly type: "validation";
303
+ readonly factory: (m: string, ve: any) => UnprocessableEntityError;
304
+ };
305
+ readonly 429: {
306
+ readonly type: "retryAfter";
307
+ readonly factory: (m: string, ra: number) => TooManyRequestsError;
308
+ };
309
+ readonly 500: {
310
+ readonly type: "standard";
311
+ readonly factory: (m: string, d: any) => InternalServerError;
312
+ };
313
+ readonly 501: {
314
+ readonly type: "standard";
315
+ readonly factory: (m: string, d: any) => NotImplementedError;
316
+ };
317
+ readonly 502: {
318
+ readonly type: "standard";
319
+ readonly factory: (m: string, d: any) => BadGatewayError;
320
+ };
321
+ readonly 503: {
322
+ readonly type: "retryAfter";
323
+ readonly factory: (m: string, ra: number) => ServiceUnavailableError;
324
+ };
325
+ readonly 504: {
326
+ readonly type: "standard";
327
+ readonly factory: (m: string, d: any) => GatewayTimeoutError;
328
+ };
329
+ };
330
+ /** Valid status codes that have registered error factories */
331
+ type ValidStatusCode = keyof typeof errorRegistry;
332
+ /** Type-safe options based on status code, ensuring correct parameters for each error type */
333
+ type ErrorOptions<T extends number> = T extends 405 ? {
334
+ allowedMethods?: string[];
335
+ code?: string;
336
+ cause?: Error;
337
+ } : T extends 422 ? {
338
+ validationErrors?: any;
339
+ code?: string;
340
+ cause?: Error;
341
+ } : T extends 429 | 503 ? {
342
+ retryAfter?: number;
343
+ code?: string;
344
+ cause?: Error;
345
+ } : {
346
+ details?: any;
347
+ code?: string;
348
+ cause?: Error;
349
+ };
350
+ /**
351
+ * Creates an HTTP error with type-safe options based on the status code.
352
+ * Provides IntelliSense support for status-code-specific options.
353
+ *
354
+ * @overload For known status codes with specific options
355
+ * @param statusCode - A valid HTTP status code from the registry
356
+ * @param message - Optional error message
357
+ * @param options - Status-code-specific options
358
+ * @returns The appropriate HttpError subclass
359
+ *
360
+ * @example
361
+ * ```typescript
362
+ * // TypeScript knows allowedMethods is valid for 405
363
+ * createHttpError(405, 'Method not allowed', { allowedMethods: ['GET', 'POST'] });
364
+ *
365
+ * // TypeScript knows retryAfter is valid for 429
366
+ * createHttpError(429, 'Rate limited', { retryAfter: 60 });
367
+ * ```
368
+ */
369
+ declare function createHttpError<T extends ValidStatusCode>(statusCode: T, message?: string, options?: ErrorOptions<T>): HttpError;
370
+ declare function createHttpError(statusCode: number, message?: string, options?: HttpErrorOptions): HttpError;
371
+ /**
372
+ * Type-safe error creation utilities with descriptive method names.
373
+ * Provides a fluent API for creating specific HTTP errors.
374
+ *
375
+ * @example
376
+ * ```typescript
377
+ * createError.notFound('User not found');
378
+ * createError.badRequest('Invalid input', { field: 'email' });
379
+ * createError.methodNotAllowed('DELETE not supported', ['GET', 'POST']);
380
+ * ```
381
+ */
382
+ declare const createError: {
383
+ readonly badRequest: (message?: string, details?: any) => BadRequestError;
384
+ readonly unauthorized: (message?: string, details?: any) => UnauthorizedError;
385
+ readonly forbidden: (message?: string, details?: any) => ForbiddenError;
386
+ readonly notFound: (message?: string, details?: any) => NotFoundError;
387
+ readonly methodNotAllowed: (message?: string, allowedMethods?: string[]) => MethodNotAllowedError;
388
+ readonly conflict: (message?: string, details?: any) => ConflictError;
389
+ readonly unprocessableEntity: (message?: string, validationErrors?: any) => UnprocessableEntityError;
390
+ readonly tooManyRequests: (message?: string, retryAfter?: number) => TooManyRequestsError;
391
+ readonly internalServerError: (message?: string, details?: any) => InternalServerError;
392
+ readonly notImplemented: (message?: string, details?: any) => NotImplementedError;
393
+ readonly badGateway: (message?: string, details?: any) => BadGatewayError;
394
+ readonly serviceUnavailable: (message?: string, retryAfter?: number) => ServiceUnavailableError;
395
+ readonly gatewayTimeout: (message?: string, details?: any) => GatewayTimeoutError;
396
+ };
397
+ /**
398
+ * Type guard to check if an error is an HttpError.
399
+ * Works with both instanceof checks and duck typing.
400
+ *
401
+ * @param error - The error to check
402
+ * @returns True if the error is an HttpError
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * try {
407
+ * // some code
408
+ * } catch (error) {
409
+ * if (isHttpError(error)) {
410
+ * console.log(`HTTP ${error.statusCode}: ${error.message}`);
411
+ * }
412
+ * }
413
+ * ```
414
+ */
415
+ declare function isHttpError(error: unknown): error is HttpError;
416
+ /**
417
+ * Type guard to check if an error is a client error (4xx status code).
418
+ *
419
+ * @param error - The error to check
420
+ * @returns True if the error is an HttpError with a 4xx status code
421
+ *
422
+ * @example
423
+ * ```typescript
424
+ * if (isClientError(error)) {
425
+ * // Log client error metrics
426
+ * }
427
+ * ```
428
+ */
429
+ declare function isClientError(error: unknown): error is HttpError;
430
+ /**
431
+ * Type guard to check if an error is a server error (5xx status code).
432
+ *
433
+ * @param error - The error to check
434
+ * @returns True if the error is an HttpError with a 5xx status code
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * if (isServerError(error)) {
439
+ * // Trigger alerts for server errors
440
+ * }
441
+ * ```
442
+ */
443
+ declare function isServerError(error: unknown): error is HttpError;
444
+ /**
445
+ * Wraps an unknown error into an HttpError.
446
+ * If the error is already an HttpError, returns it unchanged.
447
+ *
448
+ * @param error - The error to wrap
449
+ * @param statusCode - The HTTP status code to use (defaults to 500)
450
+ * @param message - Optional message to override the original error message
451
+ * @returns An HttpError instance
452
+ *
453
+ * @example
454
+ * ```typescript
455
+ * try {
456
+ * await someOperation();
457
+ * } catch (error) {
458
+ * throw wrapError(error, 503, 'Service temporarily unavailable');
459
+ * }
460
+ * ```
461
+ */
462
+ declare function wrapError(error: unknown, statusCode?: number, message?: string): HttpError;
463
+ /**
464
+ * Options for creating an HttpError.
465
+ */
466
+ interface HttpErrorOptions {
467
+ statusMessage?: string;
468
+ details?: any;
469
+ code?: string;
470
+ cause?: Error;
471
+ }
472
+ /**
473
+ * Constructor type for HttpError classes.
474
+ * Useful for factory patterns and dependency injection.
475
+ */
476
+ type HttpErrorConstructor = new (message?: string, options?: HttpErrorOptions) => HttpError;
477
+ /**
478
+ * HTTP status code enum for type-safe status code usage.
479
+ * Includes common 2xx, 3xx, 4xx, and 5xx status codes.
480
+ */
481
+ declare enum HttpStatusCode {
482
+ OK = 200,
483
+ CREATED = 201,
484
+ ACCEPTED = 202,
485
+ NO_CONTENT = 204,
486
+ MOVED_PERMANENTLY = 301,
487
+ FOUND = 302,
488
+ NOT_MODIFIED = 304,
489
+ BAD_REQUEST = 400,
490
+ UNAUTHORIZED = 401,
491
+ FORBIDDEN = 403,
492
+ NOT_FOUND = 404,
493
+ METHOD_NOT_ALLOWED = 405,
494
+ NOT_ACCEPTABLE = 406,
495
+ REQUEST_TIMEOUT = 408,
496
+ CONFLICT = 409,
497
+ GONE = 410,
498
+ UNPROCESSABLE_ENTITY = 422,
499
+ TOO_MANY_REQUESTS = 429,
500
+ INTERNAL_SERVER_ERROR = 500,
501
+ NOT_IMPLEMENTED = 501,
502
+ BAD_GATEWAY = 502,
503
+ SERVICE_UNAVAILABLE = 503,
504
+ GATEWAY_TIMEOUT = 504,
505
+ }
506
+ /**
507
+ * Namespace containing all HTTP error classes.
508
+ * Useful for importing all error types at once.
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * import { HttpErrors } from '@geekmidas/errors';
513
+ * throw new HttpErrors.NotFoundError('Resource not found');
514
+ * ```
515
+ */
516
+ declare const HttpErrors: {
517
+ HttpError: typeof HttpError;
518
+ BadRequestError: typeof BadRequestError;
519
+ UnauthorizedError: typeof UnauthorizedError;
520
+ ForbiddenError: typeof ForbiddenError;
521
+ NotFoundError: typeof NotFoundError;
522
+ MethodNotAllowedError: typeof MethodNotAllowedError;
523
+ ConflictError: typeof ConflictError;
524
+ UnprocessableEntityError: typeof UnprocessableEntityError;
525
+ TooManyRequestsError: typeof TooManyRequestsError;
526
+ InternalServerError: typeof InternalServerError;
527
+ NotImplementedError: typeof NotImplementedError;
528
+ BadGatewayError: typeof BadGatewayError;
529
+ ServiceUnavailableError: typeof ServiceUnavailableError;
530
+ GatewayTimeoutError: typeof GatewayTimeoutError;
531
+ };
532
+ //#endregion
533
+ export { BadGatewayError, BadRequestError, ConflictError, ForbiddenError, GatewayTimeoutError, HttpError, HttpErrorConstructor, HttpErrorOptions, HttpErrors, HttpStatusCode, InternalServerError, MethodNotAllowedError, NotFoundError, NotImplementedError, ServiceUnavailableError, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, createError, createHttpError, isClientError, isHttpError, isServerError, wrapError };
534
+ //# sourceMappingURL=index.d.cts.map