@naman_deep_singh/errors-utils 1.3.4 → 1.4.0

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.
Files changed (62) hide show
  1. package/README.md +37 -48
  2. package/dist/cjs/constants/errorCodes.d.ts +28 -23
  3. package/dist/cjs/constants/errorCodes.js +57 -22
  4. package/dist/cjs/constants/errorMessages.d.ts +8 -1
  5. package/dist/cjs/constants/errorMessages.js +72 -29
  6. package/dist/cjs/error/AppError.d.ts +2 -2
  7. package/dist/cjs/error/AppError.js +2 -2
  8. package/dist/cjs/error/ServiceUnavailable.d.ts +4 -0
  9. package/dist/cjs/error/ServiceUnavailable.js +11 -0
  10. package/dist/cjs/errorRegistry/errorRegistry.d.ts +19 -0
  11. package/dist/cjs/errorRegistry/errorRegistry.js +63 -0
  12. package/dist/cjs/errorRegistry/index.d.ts +3 -0
  13. package/dist/cjs/errorRegistry/index.js +6 -0
  14. package/dist/cjs/index.d.ts +1 -1
  15. package/dist/cjs/index.js +1 -3
  16. package/dist/cjs/middleware/express/{errorHandler.js → errorHandler.middleware.js} +4 -4
  17. package/dist/cjs/middleware/express/index.d.ts +2 -2
  18. package/dist/cjs/middleware/express/index.js +2 -2
  19. package/dist/esm/constants/errorCodes.d.ts +28 -23
  20. package/dist/esm/constants/errorCodes.js +57 -22
  21. package/dist/esm/constants/errorMessages.d.ts +8 -1
  22. package/dist/esm/constants/errorMessages.js +72 -29
  23. package/dist/esm/error/AppError.d.ts +2 -2
  24. package/dist/esm/error/AppError.js +2 -2
  25. package/dist/esm/error/ServiceUnavailable.d.ts +4 -0
  26. package/dist/esm/error/ServiceUnavailable.js +7 -0
  27. package/dist/esm/errorRegistry/errorRegistry.d.ts +19 -0
  28. package/dist/esm/errorRegistry/errorRegistry.js +59 -0
  29. package/dist/esm/errorRegistry/index.d.ts +3 -0
  30. package/dist/esm/errorRegistry/index.js +3 -0
  31. package/dist/esm/index.d.ts +1 -1
  32. package/dist/esm/index.js +1 -3
  33. package/dist/esm/middleware/express/{errorHandler.js → errorHandler.middleware.js} +5 -5
  34. package/dist/esm/middleware/express/index.d.ts +2 -2
  35. package/dist/esm/middleware/express/index.js +2 -2
  36. package/dist/types/constants/errorCodes.d.ts +28 -23
  37. package/dist/types/constants/errorMessages.d.ts +8 -1
  38. package/dist/types/error/AppError.d.ts +2 -2
  39. package/dist/types/error/ServiceUnavailable.d.ts +4 -0
  40. package/dist/types/errorRegistry/errorRegistry.d.ts +19 -0
  41. package/dist/types/errorRegistry/index.d.ts +3 -0
  42. package/dist/types/index.d.ts +1 -1
  43. package/dist/types/middleware/express/index.d.ts +2 -2
  44. package/package.json +1 -1
  45. package/dist/cjs/error/RateLimitError.d.ts +0 -4
  46. package/dist/cjs/error/RateLimitError.js +0 -11
  47. package/dist/cjs/utils/mapAppErrorToResponder.d.ts +0 -3
  48. package/dist/cjs/utils/mapAppErrorToResponder.js +0 -27
  49. package/dist/esm/error/RateLimitError.d.ts +0 -4
  50. package/dist/esm/error/RateLimitError.js +0 -7
  51. package/dist/esm/utils/mapAppErrorToResponder.d.ts +0 -3
  52. package/dist/esm/utils/mapAppErrorToResponder.js +0 -24
  53. package/dist/types/error/RateLimitError.d.ts +0 -4
  54. package/dist/types/utils/mapAppErrorToResponder.d.ts +0 -3
  55. /package/dist/cjs/middleware/express/{errorConverter.d.ts → errorConverter.middleware.d.ts} +0 -0
  56. /package/dist/cjs/middleware/express/{errorConverter.js → errorConverter.middleware.js} +0 -0
  57. /package/dist/cjs/middleware/express/{errorHandler.d.ts → errorHandler.middleware.d.ts} +0 -0
  58. /package/dist/esm/middleware/express/{errorConverter.d.ts → errorConverter.middleware.d.ts} +0 -0
  59. /package/dist/esm/middleware/express/{errorConverter.js → errorConverter.middleware.js} +0 -0
  60. /package/dist/esm/middleware/express/{errorHandler.d.ts → errorHandler.middleware.d.ts} +0 -0
  61. /package/dist/types/middleware/express/{errorConverter.d.ts → errorConverter.middleware.d.ts} +0 -0
  62. /package/dist/types/middleware/express/{errorHandler.d.ts → errorHandler.middleware.d.ts} +0 -0
package/README.md CHANGED
@@ -1,24 +1,20 @@
1
+ ```bash
1
2
  @naman_deep_singh/errors-utils
2
3
 
3
- Version: 1.3.4
4
+ Version: 1.4.0
4
5
 
5
6
  A standardized, code-driven error handling system for TypeScript and Express applications, providing consistent error identity, responses, and middleware integration.
6
7
 
7
8
  🚀 Features
8
9
 
9
10
  ✅ Structured Error Classes — AppError, HTTPError, ValidationError, etc.
10
-
11
11
  ✅ Strongly-Typed Error Codes — Centralized error identity via constants
12
-
13
12
  ✅ Centralized Error Messages — One source of truth for user-facing messages
14
-
15
13
  ✅ Express Middleware — Error converter & global handler
16
-
17
14
  ✅ Response Integration — Works seamlessly with @naman_deep_singh/response-utils
18
-
19
15
  ✅ TypeScript First — Full type safety & IntelliSense
20
-
21
16
  ✅ Consistent API Responses — Unified error shape across services
17
+ ✅ Extendable Error Messages — Add or override messages at runtime
22
18
 
23
19
  📦 Installation
24
20
  npm install @naman_deep_singh/errors-utils
@@ -27,19 +23,17 @@ npm install @naman_deep_singh/errors-utils
27
23
 
28
24
  This package is code-driven, not message-driven.
29
25
 
30
- Errors are identified by stable error codes
31
-
32
- Messages are resolved internally via centralized mappings
26
+ Errors are identified by stable error codes.
33
27
 
34
- API contracts remain stable even if messages change
28
+ Messages are resolved internally via centralized mappings.
35
29
 
36
- This ensures:
30
+ API contracts remain stable even if messages change.
37
31
 
38
- Consistency across microservices
32
+ Benefits:
39
33
 
40
- Safe refactoring
41
-
42
- Better logging, tracing, and observability
34
+ Consistency across microservices
35
+ ✅ Safe refactoring
36
+ Better logging, tracing, and observability
43
37
 
44
38
  🔧 Usage
45
39
  Creating Errors (Recommended)
@@ -52,12 +46,14 @@ import {
52
46
  ERROR_CODES,
53
47
  } from '@naman_deep_singh/errors-utils'
54
48
 
49
+ // Basic usage
55
50
  throw new BadRequestError(ERROR_CODES.BAD_REQUEST)
56
51
 
57
52
  throw new UnauthorizedError(ERROR_CODES.UNAUTHORIZED)
58
53
 
59
54
  throw new NotFoundError(ERROR_CODES.NOT_FOUND)
60
55
 
56
+ // With additional details
61
57
  throw new ValidationError(ERROR_CODES.VALIDATION_FAILED, {
62
58
  fields: ['email', 'password'],
63
59
  })
@@ -65,16 +61,12 @@ throw new ValidationError(ERROR_CODES.VALIDATION_FAILED, {
65
61
  throw new InternalServerError(ERROR_CODES.INTERNAL_SERVER_ERROR)
66
62
 
67
63
  🧾 Error Codes & Messages
68
-
69
- The package exposes a strongly-typed error code system.
70
-
71
64
  import {
72
65
  ERROR_CODES,
73
66
  ERROR_MESSAGES,
74
67
  ErrorCode,
75
68
  } from '@naman_deep_singh/errors-utils'
76
69
 
77
- Exports
78
70
 
79
71
  ERROR_CODES — Canonical list of all supported error codes
80
72
 
@@ -85,18 +77,11 @@ ErrorCode — Union type of all valid error codes
85
77
  Why Error Codes?
86
78
 
87
79
  ✅ Consistent error identity across services
88
-
89
80
  ✅ Centralized message management
90
-
91
81
  ✅ Safer API contracts
92
-
93
82
  ✅ Improved logging & observability
94
83
 
95
84
  🌐 Express Middleware
96
-
97
- This package provides Express-specific middleware under the hood
98
- and exposes a clean public API.
99
-
100
85
  import express from 'express'
101
86
  import {
102
87
  errorConverter,
@@ -119,21 +104,12 @@ app.post('/users', (req, res) => {
119
104
  }
120
105
  })
121
106
 
122
- Middleware Responsibilities
123
-
124
- errorConverter
125
107
 
126
- Converts unknown errors into AppError
127
-
128
- Preserves known operational errors
129
-
130
- expressErrorHandler
131
-
132
- Sends standardized API responses
108
+ Middleware Responsibilities
133
109
 
134
- Integrates with @naman_deep_singh/response-utils
110
+ errorConverter Converts unknown errors into AppError, preserves operational errors
135
111
 
136
- Hides internal errors in production
112
+ expressErrorHandler Sends standardized API responses and integrates with @naman_deep_singh/response-utils
137
113
 
138
114
  🔗 Integration
139
115
  With @naman_deep_singh/response-utils
@@ -148,17 +124,14 @@ import { createServer } from '@naman_deep_singh/server-utils'
148
124
  import { expressErrorHandler } from '@naman_deep_singh/errors-utils'
149
125
 
150
126
  const server = createServer('My API', '1.0.0')
151
-
152
127
  server.app.use(expressErrorHandler)
153
128
 
154
- 🧠 Custom Errors
129
+ 🧠 Extending & Adding Error Messages
155
130
 
156
- You can safely extend existing errors:
131
+ You can safely extend existing errors or add new codes/messages dynamically.
157
132
 
158
- import {
159
- InternalServerError,
160
- ERROR_CODES,
161
- } from '@naman_deep_singh/errors-utils'
133
+ Extending Existing Error Class
134
+ import { InternalServerError, ERROR_CODES } from '@naman_deep_singh/errors-utils'
162
135
 
163
136
  export class CryptoIntegrityError extends InternalServerError {
164
137
  constructor(details?: unknown, cause?: Error) {
@@ -166,6 +139,22 @@ export class CryptoIntegrityError extends InternalServerError {
166
139
  }
167
140
  }
168
141
 
142
+ Registering Custom Error Messages
143
+ import { errorMessageRegistry } from '@naman_deep_singh/errors-utils'
144
+
145
+ // Add new messages or override existing ones
146
+ errorMessageRegistry.register({
147
+ CUSTOM_ERROR: 'Something went wrong with custom logic',
148
+ VALIDATION_FAILED: 'Custom validation failed message',
149
+ })
150
+
151
+
152
+ After this, AppError or any derived class will use the updated messages automatically.
153
+
154
+ import { AppError } from '@naman_deep_singh/errors-utils'
155
+
156
+ throw new AppError('CUSTOM_ERROR') // message: "Something went wrong with custom logic"
157
+
169
158
  📚 Available Error Classes
170
159
  Class Status Code Use Case
171
160
  AppError Custom Base error class
@@ -179,7 +168,6 @@ NotFoundError 404 Resource not found
179
168
  ConflictError 409 Resource conflicts
180
169
  ValidationError 422 Validation errors
181
170
  RateLimitError 429 Rate limiting
182
- TooManyRequestsError 429 Alias of RateLimitError
183
171
  CryptoIntegrityError 500 Crypto validation failure
184
172
  InternalServerError 500 Server-side failures
185
173
  🎯 Standard Error Response
@@ -197,4 +185,5 @@ All errors resolve to a consistent response shape:
197
185
 
198
186
  📄 License
199
187
 
200
- ISC © Naman Deep Singh
188
+ ISC © Naman Deep Singh
189
+ ```
@@ -1,32 +1,37 @@
1
1
  export declare const ERROR_CODES: {
2
2
  readonly BAD_REQUEST: "BAD_REQUEST";
3
+ readonly VALIDATION_FAILED: "VALIDATION_FAILED";
3
4
  readonly UNAUTHORIZED: "UNAUTHORIZED";
4
5
  readonly FORBIDDEN: "FORBIDDEN";
5
6
  readonly NOT_FOUND: "NOT_FOUND";
6
7
  readonly CONFLICT: "CONFLICT";
7
- readonly VALIDATION_FAILED: "VALIDATION_FAILED";
8
- readonly RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED";
9
- readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
10
- readonly CRYPTO_INTEGRITY_ERROR: "CRYPTO_INTEGRITY_ERROR";
11
8
  readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
12
- readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
9
+ readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
10
+ readonly SERVICE_UNAVAILABLE: "SERVICE_UNAVAILABLE";
11
+ readonly DEPENDENCY_FAILURE: "DEPENDENCY_FAILURE";
12
+ readonly HTTP_ERROR: "HTTP_ERROR";
13
+ readonly HTTP_TIMEOUT: "HTTP_TIMEOUT";
14
+ readonly UPSTREAM_SERVICE_ERROR: "UPSTREAM_SERVICE_ERROR";
15
+ readonly AUTH_FAILED: "AUTH_FAILED";
16
+ readonly TOKEN_MISSING: "TOKEN_MISSING";
13
17
  readonly TOKEN_INVALID: "TOKEN_INVALID";
14
- readonly TOKEN_NOT_PROVIDED: "TOKEN_NOT_PROVIDED";
15
- readonly TOKEN_NOT_FOUND: "TOKEN_NOT_FOUND";
16
- readonly TOKEN_NOT_CREATED: "TOKEN_NOT_CREATED";
17
- readonly TOKEN_NOT_UPDATED: "TOKEN_NOT_UPDATED";
18
- readonly TOKEN_NOT_DELETED: "TOKEN_NOT_DELETED";
19
- readonly TOKEN_NOT_VALIDATED: "TOKEN_NOT_VALIDATED";
20
- readonly TOKEN_NOT_REFRESHED: "TOKEN_NOT_REFRESHED";
21
- readonly TOKEN_NOT_REVOKED: "TOKEN_NOT_REVOKED";
22
- readonly TOKEN_NOT_BLACKLISTED: "TOKEN_NOT_BLACKLISTED";
23
- readonly TOKEN_NOT_WHITELISTED: "TOKEN_NOT_WHITELISTED";
24
- readonly TOKEN_NOT_DECODED: "TOKEN_NOT_DECODED";
25
- readonly TOKEN_NOT_ENCODED: "TOKEN_NOT_ENCODED";
26
- readonly TOKEN_NOT_SIGNED: "TOKEN_NOT_SIGNED";
27
- readonly TOKEN_NOT_VERIFIED: "TOKEN_NOT_VERIFIED";
28
- readonly TOKEN_NOT_DECRYPTED: "TOKEN_NOT_DECRYPTED";
29
- readonly TOKEN_NOT_ENCRYPTED: "TOKEN_NOT_ENCRYPTED";
30
- readonly TOKEN_NOT_GENERATED: "TOKEN_NOT_GENERATED";
18
+ readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
19
+ readonly CRYPTO_ERROR: "CRYPTO_ERROR";
20
+ readonly CRYPTO_INTEGRITY_ERROR: "CRYPTO_INTEGRITY_ERROR";
21
+ readonly CACHE_ERROR: "CACHE_ERROR";
22
+ readonly CACHE_CONNECTION_FAILED: "CACHE_CONNECTION_FAILED";
23
+ readonly DATABASE_ERROR: "DATABASE_ERROR";
24
+ readonly DATABASE_CONNECTION_FAILED: "DATABASE_CONNECTION_FAILED";
25
+ readonly DATABASE_CONSTRAINT_VIOLATION: "DATABASE_CONSTRAINT_VIOLATION";
26
+ readonly MESSAGE_BROKER_ERROR: "MESSAGE_BROKER_ERROR";
27
+ readonly MESSAGE_PUBLISH_FAILED: "MESSAGE_PUBLISH_FAILED";
28
+ readonly FILE_ERROR: "FILE_ERROR";
29
+ readonly FILE_NOT_FOUND: "FILE_NOT_FOUND";
30
+ readonly FILE_UPLOAD_FAILED: "FILE_UPLOAD_FAILED";
31
+ readonly FILE_TOO_LARGE: "FILE_TOO_LARGE";
32
+ readonly CONFIG_ERROR: "CONFIG_ERROR";
33
+ readonly CONFIG_MISSING: "CONFIG_MISSING";
34
+ readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
35
+ readonly RESOURCE_EXHAUSTED: "RESOURCE_EXHAUSTED";
31
36
  };
32
- export type ErrorCode = keyof typeof ERROR_CODES;
37
+ export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
@@ -2,33 +2,68 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ERROR_CODES = void 0;
4
4
  exports.ERROR_CODES = {
5
+ /* ------------------------------------------------------------------ */
6
+ /* 🧱 Common / Generic */
7
+ /* ------------------------------------------------------------------ */
5
8
  BAD_REQUEST: 'BAD_REQUEST',
9
+ VALIDATION_FAILED: 'VALIDATION_FAILED',
6
10
  UNAUTHORIZED: 'UNAUTHORIZED',
7
11
  FORBIDDEN: 'FORBIDDEN',
8
12
  NOT_FOUND: 'NOT_FOUND',
9
13
  CONFLICT: 'CONFLICT',
10
- VALIDATION_FAILED: 'VALIDATION_FAILED',
11
- RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
12
- INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',
13
- CRYPTO_INTEGRITY_ERROR: 'CRYPTO_INTEGRITY_ERROR',
14
14
  TOO_MANY_REQUESTS: 'TOO_MANY_REQUESTS',
15
- TOKEN_EXPIRED: 'TOKEN_EXPIRED',
15
+ INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',
16
+ SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',
17
+ DEPENDENCY_FAILURE: 'DEPENDENCY_FAILURE',
18
+ /* ------------------------------------------------------------------ */
19
+ /* 🌐 HTTP / Network */
20
+ /* ------------------------------------------------------------------ */
21
+ HTTP_ERROR: 'HTTP_ERROR',
22
+ HTTP_TIMEOUT: 'HTTP_TIMEOUT',
23
+ UPSTREAM_SERVICE_ERROR: 'UPSTREAM_SERVICE_ERROR',
24
+ /* ------------------------------------------------------------------ */
25
+ /* 🔐 Authentication / Authorization */
26
+ /* ------------------------------------------------------------------ */
27
+ AUTH_FAILED: 'AUTH_FAILED',
28
+ TOKEN_MISSING: 'TOKEN_MISSING',
16
29
  TOKEN_INVALID: 'TOKEN_INVALID',
17
- TOKEN_NOT_PROVIDED: 'TOKEN_NOT_PROVIDED',
18
- TOKEN_NOT_FOUND: 'TOKEN_NOT_FOUND',
19
- TOKEN_NOT_CREATED: 'TOKEN_NOT_CREATED',
20
- TOKEN_NOT_UPDATED: 'TOKEN_NOT_UPDATED',
21
- TOKEN_NOT_DELETED: 'TOKEN_NOT_DELETED',
22
- TOKEN_NOT_VALIDATED: 'TOKEN_NOT_VALIDATED',
23
- TOKEN_NOT_REFRESHED: 'TOKEN_NOT_REFRESHED',
24
- TOKEN_NOT_REVOKED: 'TOKEN_NOT_REVOKED',
25
- TOKEN_NOT_BLACKLISTED: 'TOKEN_NOT_BLACKLISTED',
26
- TOKEN_NOT_WHITELISTED: 'TOKEN_NOT_WHITELISTED',
27
- TOKEN_NOT_DECODED: 'TOKEN_NOT_DECODED',
28
- TOKEN_NOT_ENCODED: 'TOKEN_NOT_ENCODED',
29
- TOKEN_NOT_SIGNED: 'TOKEN_NOT_SIGNED',
30
- TOKEN_NOT_VERIFIED: 'TOKEN_NOT_VERIFIED',
31
- TOKEN_NOT_DECRYPTED: 'TOKEN_NOT_DECRYPTED',
32
- TOKEN_NOT_ENCRYPTED: 'TOKEN_NOT_ENCRYPTED',
33
- TOKEN_NOT_GENERATED: 'TOKEN_NOT_GENERATED',
30
+ TOKEN_EXPIRED: 'TOKEN_EXPIRED',
31
+ /* ------------------------------------------------------------------ */
32
+ /* 🔑 Cryptography / Security */
33
+ /* ------------------------------------------------------------------ */
34
+ CRYPTO_ERROR: 'CRYPTO_ERROR',
35
+ CRYPTO_INTEGRITY_ERROR: 'CRYPTO_INTEGRITY_ERROR',
36
+ /* ------------------------------------------------------------------ */
37
+ /* 💾 Cache */
38
+ /* ------------------------------------------------------------------ */
39
+ CACHE_ERROR: 'CACHE_ERROR',
40
+ CACHE_CONNECTION_FAILED: 'CACHE_CONNECTION_FAILED',
41
+ /* ------------------------------------------------------------------ */
42
+ /* 🗄️ Database */
43
+ /* ------------------------------------------------------------------ */
44
+ DATABASE_ERROR: 'DATABASE_ERROR',
45
+ DATABASE_CONNECTION_FAILED: 'DATABASE_CONNECTION_FAILED',
46
+ DATABASE_CONSTRAINT_VIOLATION: 'DATABASE_CONSTRAINT_VIOLATION',
47
+ /* ------------------------------------------------------------------ */
48
+ /* 📩 Messaging / Queues */
49
+ /* ------------------------------------------------------------------ */
50
+ MESSAGE_BROKER_ERROR: 'MESSAGE_BROKER_ERROR',
51
+ MESSAGE_PUBLISH_FAILED: 'MESSAGE_PUBLISH_FAILED',
52
+ /* ------------------------------------------------------------------ */
53
+ /* 📁 File / Storage */
54
+ /* ------------------------------------------------------------------ */
55
+ FILE_ERROR: 'FILE_ERROR',
56
+ FILE_NOT_FOUND: 'FILE_NOT_FOUND',
57
+ FILE_UPLOAD_FAILED: 'FILE_UPLOAD_FAILED',
58
+ FILE_TOO_LARGE: 'FILE_TOO_LARGE',
59
+ /* ------------------------------------------------------------------ */
60
+ /* ⚙️ Configuration / Environment */
61
+ /* ------------------------------------------------------------------ */
62
+ CONFIG_ERROR: 'CONFIG_ERROR',
63
+ CONFIG_MISSING: 'CONFIG_MISSING',
64
+ /* ------------------------------------------------------------------ */
65
+ /* ⏱️ Timeouts / Resources */
66
+ /* ------------------------------------------------------------------ */
67
+ TIMEOUT_ERROR: 'TIMEOUT_ERROR',
68
+ RESOURCE_EXHAUSTED: 'RESOURCE_EXHAUSTED',
34
69
  };
@@ -1,2 +1,9 @@
1
- import type { ErrorCode } from './errorCodes';
1
+ import { type ErrorCode } from './errorCodes';
2
+ /**
3
+ * Canonical error messages mapped to ERROR_CODES
4
+ * - Human-readable
5
+ * - Safe for API responses
6
+ * - Useful for logs
7
+ * - Can be overridden by services if needed
8
+ */
2
9
  export declare const ERROR_MESSAGES: Record<ErrorCode, string>;
@@ -1,34 +1,77 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ERROR_MESSAGES = void 0;
4
+ const errorCodes_1 = require("./errorCodes");
5
+ /**
6
+ * Canonical error messages mapped to ERROR_CODES
7
+ * - Human-readable
8
+ * - Safe for API responses
9
+ * - Useful for logs
10
+ * - Can be overridden by services if needed
11
+ */
4
12
  exports.ERROR_MESSAGES = {
5
- BAD_REQUEST: 'Bad request',
6
- UNAUTHORIZED: 'Unauthorized',
7
- FORBIDDEN: 'Forbidden',
8
- NOT_FOUND: 'Resource not found',
9
- CONFLICT: 'Conflict occurred',
10
- VALIDATION_FAILED: 'Validation failed',
11
- RATE_LIMIT_EXCEEDED: 'Too many requests',
12
- INTERNAL_SERVER_ERROR: 'Internal server error',
13
- CRYPTO_INTEGRITY_ERROR: 'Crypto integrity error',
14
- TOO_MANY_REQUESTS: 'Too many requests',
15
- TOKEN_EXPIRED: 'Token expired',
16
- TOKEN_INVALID: 'Invalid token',
17
- TOKEN_NOT_PROVIDED: 'Token not provided',
18
- TOKEN_NOT_FOUND: 'Token not found',
19
- TOKEN_NOT_CREATED: 'Token not created',
20
- TOKEN_NOT_UPDATED: 'Token not updated',
21
- TOKEN_NOT_DELETED: 'Token not deleted',
22
- TOKEN_NOT_VALIDATED: 'Token not validated',
23
- TOKEN_NOT_REFRESHED: 'Token not refreshed',
24
- TOKEN_NOT_REVOKED: 'Token not revoked',
25
- TOKEN_NOT_BLACKLISTED: 'Token not blacklisted',
26
- TOKEN_NOT_WHITELISTED: 'Token not whitelisted',
27
- TOKEN_NOT_DECODED: 'Token not decoded',
28
- TOKEN_NOT_ENCODED: 'Token not encoded',
29
- TOKEN_NOT_SIGNED: 'Token not signed',
30
- TOKEN_NOT_VERIFIED: 'Token not verified',
31
- TOKEN_NOT_DECRYPTED: 'Token not decrypted',
32
- TOKEN_NOT_ENCRYPTED: 'Token not encrypted',
33
- TOKEN_NOT_GENERATED: 'Token not generated',
13
+ /* ------------------------------------------------------------------ */
14
+ /* 🧱 Common / Generic */
15
+ /* ------------------------------------------------------------------ */
16
+ [errorCodes_1.ERROR_CODES.BAD_REQUEST]: 'The request is invalid or malformed.',
17
+ [errorCodes_1.ERROR_CODES.VALIDATION_FAILED]: 'Request validation failed.',
18
+ [errorCodes_1.ERROR_CODES.UNAUTHORIZED]: 'Authentication is required.',
19
+ [errorCodes_1.ERROR_CODES.FORBIDDEN]: 'You do not have permission to perform this action.',
20
+ [errorCodes_1.ERROR_CODES.NOT_FOUND]: 'The requested resource was not found.',
21
+ [errorCodes_1.ERROR_CODES.CONFLICT]: 'The request could not be completed due to a conflict.',
22
+ [errorCodes_1.ERROR_CODES.TOO_MANY_REQUESTS]: 'Too many requests. Please try again later.',
23
+ [errorCodes_1.ERROR_CODES.INTERNAL_SERVER_ERROR]: 'An unexpected internal error occurred.',
24
+ [errorCodes_1.ERROR_CODES.SERVICE_UNAVAILABLE]: 'The service is currently unavailable.',
25
+ [errorCodes_1.ERROR_CODES.DEPENDENCY_FAILURE]: 'A dependent service failed to respond.',
26
+ /* ------------------------------------------------------------------ */
27
+ /* 🌐 HTTP / Network */
28
+ /* ------------------------------------------------------------------ */
29
+ [errorCodes_1.ERROR_CODES.HTTP_ERROR]: 'An HTTP error occurred while processing the request.',
30
+ [errorCodes_1.ERROR_CODES.HTTP_TIMEOUT]: 'The request timed out.',
31
+ [errorCodes_1.ERROR_CODES.UPSTREAM_SERVICE_ERROR]: 'An upstream service returned an error.',
32
+ /* ------------------------------------------------------------------ */
33
+ /* 🔐 Authentication / Authorization */
34
+ /* ------------------------------------------------------------------ */
35
+ [errorCodes_1.ERROR_CODES.AUTH_FAILED]: 'Authentication failed.',
36
+ [errorCodes_1.ERROR_CODES.TOKEN_MISSING]: 'Authentication token is missing.',
37
+ [errorCodes_1.ERROR_CODES.TOKEN_INVALID]: 'Authentication token is invalid.',
38
+ [errorCodes_1.ERROR_CODES.TOKEN_EXPIRED]: 'Authentication token has expired.',
39
+ /* ------------------------------------------------------------------ */
40
+ /* 🔑 Cryptography / Security */
41
+ /* ------------------------------------------------------------------ */
42
+ [errorCodes_1.ERROR_CODES.CRYPTO_ERROR]: 'A cryptographic operation failed.',
43
+ [errorCodes_1.ERROR_CODES.CRYPTO_INTEGRITY_ERROR]: 'Data integrity verification failed.',
44
+ /* ------------------------------------------------------------------ */
45
+ /* 💾 Cache */
46
+ /* ------------------------------------------------------------------ */
47
+ [errorCodes_1.ERROR_CODES.CACHE_ERROR]: 'A cache operation failed.',
48
+ [errorCodes_1.ERROR_CODES.CACHE_CONNECTION_FAILED]: 'Failed to connect to the cache store.',
49
+ /* ------------------------------------------------------------------ */
50
+ /* 🗄️ Database */
51
+ /* ------------------------------------------------------------------ */
52
+ [errorCodes_1.ERROR_CODES.DATABASE_ERROR]: 'A database error occurred.',
53
+ [errorCodes_1.ERROR_CODES.DATABASE_CONNECTION_FAILED]: 'Failed to connect to the database.',
54
+ [errorCodes_1.ERROR_CODES.DATABASE_CONSTRAINT_VIOLATION]: 'The operation violates a database constraint.',
55
+ /* ------------------------------------------------------------------ */
56
+ /* 📩 Messaging / Queues */
57
+ /* ------------------------------------------------------------------ */
58
+ [errorCodes_1.ERROR_CODES.MESSAGE_BROKER_ERROR]: 'A message broker error occurred.',
59
+ [errorCodes_1.ERROR_CODES.MESSAGE_PUBLISH_FAILED]: 'Failed to publish message to the message broker.',
60
+ /* ------------------------------------------------------------------ */
61
+ /* 📁 File / Storage */
62
+ /* ------------------------------------------------------------------ */
63
+ [errorCodes_1.ERROR_CODES.FILE_ERROR]: 'A file operation failed.',
64
+ [errorCodes_1.ERROR_CODES.FILE_NOT_FOUND]: 'The requested file was not found.',
65
+ [errorCodes_1.ERROR_CODES.FILE_UPLOAD_FAILED]: 'File upload failed.',
66
+ [errorCodes_1.ERROR_CODES.FILE_TOO_LARGE]: 'The uploaded file exceeds the allowed size.',
67
+ /* ------------------------------------------------------------------ */
68
+ /* ⚙️ Configuration / Environment */
69
+ /* ------------------------------------------------------------------ */
70
+ [errorCodes_1.ERROR_CODES.CONFIG_ERROR]: 'Configuration error detected.',
71
+ [errorCodes_1.ERROR_CODES.CONFIG_MISSING]: 'Required configuration is missing.',
72
+ /* ------------------------------------------------------------------ */
73
+ /* ⏱️ Timeouts / Resources */
74
+ /* ------------------------------------------------------------------ */
75
+ [errorCodes_1.ERROR_CODES.TIMEOUT_ERROR]: 'The operation timed out.',
76
+ [errorCodes_1.ERROR_CODES.RESOURCE_EXHAUSTED]: 'The system has exhausted required resources.',
34
77
  };
@@ -1,4 +1,4 @@
1
- import { type ErrorCode } from '../constants';
1
+ import type { ErrorCode } from '../constants';
2
2
  export declare class AppError extends Error {
3
3
  statusCode: number;
4
4
  isOperational: boolean;
@@ -8,7 +8,7 @@ export declare class AppError extends Error {
8
8
  constructor(code: ErrorCode, statusCode?: number, details?: unknown, cause?: Error);
9
9
  toJSON(): {
10
10
  success: boolean;
11
- code: "BAD_REQUEST" | "UNAUTHORIZED" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "VALIDATION_FAILED" | "RATE_LIMIT_EXCEEDED" | "INTERNAL_SERVER_ERROR" | "CRYPTO_INTEGRITY_ERROR" | "TOO_MANY_REQUESTS" | "TOKEN_EXPIRED" | "TOKEN_INVALID" | "TOKEN_NOT_PROVIDED" | "TOKEN_NOT_FOUND" | "TOKEN_NOT_CREATED" | "TOKEN_NOT_UPDATED" | "TOKEN_NOT_DELETED" | "TOKEN_NOT_VALIDATED" | "TOKEN_NOT_REFRESHED" | "TOKEN_NOT_REVOKED" | "TOKEN_NOT_BLACKLISTED" | "TOKEN_NOT_WHITELISTED" | "TOKEN_NOT_DECODED" | "TOKEN_NOT_ENCODED" | "TOKEN_NOT_SIGNED" | "TOKEN_NOT_VERIFIED" | "TOKEN_NOT_DECRYPTED" | "TOKEN_NOT_ENCRYPTED" | "TOKEN_NOT_GENERATED";
11
+ code: ErrorCode;
12
12
  message: string;
13
13
  details: {} | null;
14
14
  };
@@ -2,10 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AppError = void 0;
4
4
  const response_utils_1 = require("@naman_deep_singh/response-utils");
5
- const constants_1 = require("../constants");
5
+ const src_1 = require("src");
6
6
  class AppError extends Error {
7
7
  constructor(code, statusCode = response_utils_1.HTTP_STATUS.SERVER_ERROR.INTERNAL_SERVER_ERROR, details, cause) {
8
- super(constants_1.ERROR_MESSAGES[code]); // message comes from mapping
8
+ super(src_1.errorMessageRegistry.resolve(code)); // message comes from mapping
9
9
  this.code = code;
10
10
  this.statusCode = statusCode;
11
11
  this.isOperational = true;
@@ -0,0 +1,4 @@
1
+ import { InternalServerError } from './InternalServerError';
2
+ export declare class ServiceUnavailableError extends InternalServerError {
3
+ constructor(details?: unknown, cause?: Error);
4
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServiceUnavailableError = void 0;
4
+ const constants_1 = require("src/constants");
5
+ const InternalServerError_1 = require("./InternalServerError");
6
+ class ServiceUnavailableError extends InternalServerError_1.InternalServerError {
7
+ constructor(details, cause) {
8
+ super(constants_1.ERROR_CODES.SERVICE_UNAVAILABLE, details, cause);
9
+ }
10
+ }
11
+ exports.ServiceUnavailableError = ServiceUnavailableError;
@@ -0,0 +1,19 @@
1
+ import type { ExpressResponder } from '@naman_deep_singh/response-utils';
2
+ import { type ErrorCode } from 'src/constants';
3
+ import type { AppError } from 'src/error/AppError';
4
+ export declare class ErrorMessageRegistry {
5
+ private static instance;
6
+ private readonly registry;
7
+ private constructor();
8
+ /** Singleton accessor */
9
+ static getInstance(): ErrorMessageRegistry;
10
+ /** Register or override messages */
11
+ register(messages: Record<string, string>): void;
12
+ /** Resolve a message for a given error code */
13
+ resolve(code: ErrorCode | string, defaultMessage?: string): string;
14
+ /**
15
+ * Map an AppError to an ExpressResponder
16
+ * Centralizes error-to-HTTP mapping
17
+ */
18
+ mapAppErrorToResponder(responder: ExpressResponder<unknown>, err: AppError): any;
19
+ }
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ErrorMessageRegistry = void 0;
4
+ const response_utils_1 = require("@naman_deep_singh/response-utils");
5
+ const constants_1 = require("src/constants");
6
+ class ErrorMessageRegistry {
7
+ constructor() {
8
+ this.registry = new Map();
9
+ // Initialize with default messages
10
+ Object.entries(constants_1.ERROR_MESSAGES).forEach(([code, message]) => {
11
+ this.registry.set(code, message);
12
+ });
13
+ }
14
+ /** Singleton accessor */
15
+ static getInstance() {
16
+ if (!ErrorMessageRegistry.instance) {
17
+ ErrorMessageRegistry.instance = new ErrorMessageRegistry();
18
+ }
19
+ return ErrorMessageRegistry.instance;
20
+ }
21
+ /** Register or override messages */
22
+ register(messages) {
23
+ for (const [code, message] of Object.entries(messages)) {
24
+ this.registry.set(code, message);
25
+ }
26
+ }
27
+ /** Resolve a message for a given error code */
28
+ resolve(code, defaultMessage = 'Unexpected error') {
29
+ return this.registry.get(code) ?? defaultMessage;
30
+ }
31
+ /**
32
+ * Map an AppError to an ExpressResponder
33
+ * Centralizes error-to-HTTP mapping
34
+ */
35
+ mapAppErrorToResponder(responder, err) {
36
+ switch (err.statusCode) {
37
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.BAD_REQUEST:
38
+ return responder.badRequest(this.resolve(err.code), {
39
+ details: err.details,
40
+ });
41
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.UNAUTHORIZED:
42
+ return responder.unauthorized(this.resolve(err.code));
43
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.FORBIDDEN:
44
+ return responder.forbidden(this.resolve(err.code));
45
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.NOT_FOUND:
46
+ return responder.notFound(this.resolve(err.code));
47
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.CONFLICT:
48
+ return responder.conflict(this.resolve(err.code));
49
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.UNPROCESSABLE_ENTITY:
50
+ return responder.unprocessableEntity(this.resolve(err.code), {
51
+ details: err.details,
52
+ });
53
+ case response_utils_1.HTTP_STATUS.CLIENT_ERROR.TOO_MANY_REQUESTS:
54
+ return responder.tooManyRequests(this.resolve(err.code));
55
+ default:
56
+ // Any other status maps to generic server error
57
+ return responder.serverError(this.resolve(err.code), {
58
+ details: err.details,
59
+ });
60
+ }
61
+ }
62
+ }
63
+ exports.ErrorMessageRegistry = ErrorMessageRegistry;
@@ -0,0 +1,3 @@
1
+ import { ErrorMessageRegistry } from './errorRegistry';
2
+ /** Singleton export for easy access */
3
+ export declare const errorMessageRegistry: ErrorMessageRegistry;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorMessageRegistry = void 0;
4
+ const errorRegistry_1 = require("./errorRegistry");
5
+ /** Singleton export for easy access */
6
+ exports.errorMessageRegistry = errorRegistry_1.ErrorMessageRegistry.getInstance();
@@ -1,3 +1,4 @@
1
+ export * from './errorRegistry';
1
2
  export * from './error/AppError';
2
3
  export * from './error/HTTPError';
3
4
  export * from './error/BadRequestError';
@@ -6,7 +7,6 @@ export * from './error/ForbiddenError';
6
7
  export * from './error/NotFoundError';
7
8
  export * from './error/ConflictError';
8
9
  export * from './error/ValidationError';
9
- export * from './error/RateLimitError';
10
10
  export * from './error/TooManyRequestsError';
11
11
  export * from './error/TokenExpiredError';
12
12
  export * from './error/TokenMalformedError';
package/dist/cjs/index.js CHANGED
@@ -14,8 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- // =========================
18
- // Base Errors
17
+ __exportStar(require("./errorRegistry"), exports);
19
18
  // =========================
20
19
  __exportStar(require("./error/AppError"), exports);
21
20
  __exportStar(require("./error/HTTPError"), exports);
@@ -28,7 +27,6 @@ __exportStar(require("./error/ForbiddenError"), exports);
28
27
  __exportStar(require("./error/NotFoundError"), exports);
29
28
  __exportStar(require("./error/ConflictError"), exports);
30
29
  __exportStar(require("./error/ValidationError"), exports);
31
- __exportStar(require("./error/RateLimitError"), exports);
32
30
  __exportStar(require("./error/TooManyRequestsError"), exports);
33
31
  // =========================
34
32
  // Auth / Token Errors