create-charcole 1.0.0 → 2.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.
Files changed (73) hide show
  1. package/.github/workflows/release.yml +26 -0
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +11 -1
  4. package/bin/index.js +94 -49
  5. package/bin/lib/pkgManager.js +66 -0
  6. package/bin/lib/templateHandler.js +70 -0
  7. package/package.json +4 -1
  8. package/template/js/basePackage.json +28 -0
  9. package/template/{package-lock.json → js/package-lock.json} +1253 -1253
  10. package/template/{package.json → js/package.json} +28 -28
  11. package/template/ts/.env.example +8 -0
  12. package/template/ts/ARCHITECTURE_DIAGRAMS.md +283 -0
  13. package/template/ts/CHECKLIST.md +279 -0
  14. package/template/ts/COMPLETE.md +405 -0
  15. package/template/ts/ERROR_HANDLING.md +393 -0
  16. package/template/ts/IMPLEMENTATION.md +368 -0
  17. package/template/ts/IMPLEMENTATION_COMPLETE.md +363 -0
  18. package/template/ts/INDEX.md +290 -0
  19. package/template/ts/QUICK_REFERENCE.md +270 -0
  20. package/template/ts/README.md +855 -0
  21. package/template/ts/basePackage.json +36 -0
  22. package/template/ts/package-lock.json +2428 -0
  23. package/template/ts/package.json +32 -0
  24. package/template/ts/src/app.js +75 -0
  25. package/template/ts/src/app.ts +66 -0
  26. package/template/ts/src/config/constants.js +20 -0
  27. package/template/ts/src/config/constants.ts +27 -0
  28. package/template/ts/src/config/env.js +26 -0
  29. package/template/ts/src/config/env.ts +40 -0
  30. package/template/ts/src/middlewares/errorHandler.js +180 -0
  31. package/template/ts/src/middlewares/errorHandler.ts +209 -0
  32. package/template/ts/src/middlewares/requestLogger.js +33 -0
  33. package/template/ts/src/middlewares/requestLogger.ts +38 -0
  34. package/template/ts/src/middlewares/validateRequest.js +42 -0
  35. package/template/ts/src/middlewares/validateRequest.ts +46 -0
  36. package/template/ts/src/modules/health/controller.js +50 -0
  37. package/template/ts/src/modules/health/controller.ts +64 -0
  38. package/template/ts/src/routes.js +17 -0
  39. package/template/ts/src/routes.ts +16 -0
  40. package/template/ts/src/server.js +38 -0
  41. package/template/ts/src/server.ts +42 -0
  42. package/template/ts/src/types/express.d.ts +9 -0
  43. package/template/ts/src/utils/AppError.js +182 -0
  44. package/template/ts/src/utils/AppError.ts +220 -0
  45. package/template/ts/src/utils/logger.js +73 -0
  46. package/template/ts/src/utils/logger.ts +55 -0
  47. package/template/ts/src/utils/response.js +51 -0
  48. package/template/ts/src/utils/response.ts +100 -0
  49. package/template/ts/test-api.js +100 -0
  50. package/template/ts/tsconfig.json +19 -0
  51. /package/template/{.env.example → js/.env.example} +0 -0
  52. /package/template/{ARCHITECTURE_DIAGRAMS.md → js/ARCHITECTURE_DIAGRAMS.md} +0 -0
  53. /package/template/{CHECKLIST.md → js/CHECKLIST.md} +0 -0
  54. /package/template/{COMPLETE.md → js/COMPLETE.md} +0 -0
  55. /package/template/{ERROR_HANDLING.md → js/ERROR_HANDLING.md} +0 -0
  56. /package/template/{IMPLEMENTATION.md → js/IMPLEMENTATION.md} +0 -0
  57. /package/template/{IMPLEMENTATION_COMPLETE.md → js/IMPLEMENTATION_COMPLETE.md} +0 -0
  58. /package/template/{INDEX.md → js/INDEX.md} +0 -0
  59. /package/template/{QUICK_REFERENCE.md → js/QUICK_REFERENCE.md} +0 -0
  60. /package/template/{README.md → js/README.md} +0 -0
  61. /package/template/{src → js/src}/app.js +0 -0
  62. /package/template/{src → js/src}/config/constants.js +0 -0
  63. /package/template/{src → js/src}/config/env.js +0 -0
  64. /package/template/{src → js/src}/middlewares/errorHandler.js +0 -0
  65. /package/template/{src → js/src}/middlewares/requestLogger.js +0 -0
  66. /package/template/{src → js/src}/middlewares/validateRequest.js +0 -0
  67. /package/template/{src → js/src}/modules/health/controller.js +0 -0
  68. /package/template/{src → js/src}/routes.js +0 -0
  69. /package/template/{src → js/src}/server.js +0 -0
  70. /package/template/{src → js/src}/utils/AppError.js +0 -0
  71. /package/template/{src → js/src}/utils/logger.js +0 -0
  72. /package/template/{src → js/src}/utils/response.js +0 -0
  73. /package/template/{test-api.js → js/test-api.js} +0 -0
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "charcole",
3
+ "version": "1.0.0",
4
+ "description": "Production-grade Node.js Express API",
5
+ "main": "src/server.js",
6
+ "scripts": {
7
+ "start": "node src/server.js",
8
+ "dev": "nodemon src/server.js",
9
+ "lint": "echo 'Add linting here'",
10
+ "test": "echo 'Add tests here'"
11
+ },
12
+ "engines": {
13
+ "node": ">=18.0.0"
14
+ },
15
+ "keywords": [],
16
+ "author": "",
17
+ "license": "ISC",
18
+ "type": "module",
19
+ "dependencies": {
20
+ "cors": "^2.8.5",
21
+ "dotenv": "^16.3.1",
22
+ "express": "^4.18.2",
23
+ "zod": "^3.22.4"
24
+ },
25
+ "devDependencies": {
26
+ "@types/express": "^5.0.6",
27
+ "@types/node": "^25.0.10",
28
+ "nodemon": "^3.0.2",
29
+ "ts-node-dev": "^2.0.0",
30
+ "typescript": "^5.9.3"
31
+ }
32
+ }
@@ -0,0 +1,75 @@
1
+ import express from "express";
2
+ import cors from "cors";
3
+ import { env } from "./config/env.js";
4
+ import { HTTP_STATUS, ERROR_MESSAGES } from "./config/constants.js";
5
+ import { requestLogger } from "./middlewares/requestLogger.js";
6
+ import {
7
+ errorHandler,
8
+ asyncHandler,
9
+ NotFoundError,
10
+ } from "./middlewares/errorHandler.js";
11
+ import { sendSuccess } from "./utils/response.js";
12
+ import { logger } from "./utils/logger.js";
13
+ import routes from "./routes.js";
14
+
15
+ export const app = express();
16
+
17
+ // Trust proxy
18
+ app.set("trust proxy", 1);
19
+
20
+ // CORS Configuration
21
+ app.use(
22
+ cors({
23
+ origin: env.CORS_ORIGIN,
24
+ credentials: true,
25
+ methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
26
+ allowedHeaders: ["Content-Type", "Authorization"],
27
+ }),
28
+ );
29
+
30
+ // Body parsing middleware
31
+ app.use(express.json({ limit: "10mb" }));
32
+ app.use(express.urlencoded({ extended: true, limit: "10mb" }));
33
+
34
+ // Request timeout
35
+ app.use((req, res, next) => {
36
+ req.setTimeout(env.REQUEST_TIMEOUT);
37
+ res.setTimeout(env.REQUEST_TIMEOUT);
38
+ next();
39
+ });
40
+
41
+ // Request logging
42
+ app.use(requestLogger);
43
+
44
+ // API Routes
45
+ app.use("/api", routes);
46
+
47
+ // Root health endpoint
48
+ app.get(
49
+ "/",
50
+ asyncHandler(async (req, res) => {
51
+ sendSuccess(
52
+ res,
53
+ {
54
+ message: "Welcome to Charcole API",
55
+ version: "1.0.0",
56
+ environment: env.NODE_ENV,
57
+ },
58
+ 200,
59
+ "API is online",
60
+ );
61
+ }),
62
+ );
63
+
64
+ // 404 handler
65
+ app.use((req, res, next) => {
66
+ throw new NotFoundError(`${req.method} ${req.path}`, {
67
+ method: req.method,
68
+ path: req.path,
69
+ });
70
+ });
71
+
72
+ // Global error handler (MUST be last)
73
+ app.use(errorHandler);
74
+
75
+ logger.info("Express app configured successfully");
@@ -0,0 +1,66 @@
1
+ import express, { Request, Response, NextFunction } from "express";
2
+ import cors from "cors";
3
+
4
+ import { env } from "./config/env.js";
5
+ import { requestLogger } from "./middlewares/requestLogger.js";
6
+ import {
7
+ errorHandler,
8
+ asyncHandler,
9
+ NotFoundError,
10
+ } from "./middlewares/errorHandler.js";
11
+ import { sendSuccess } from "./utils/response.js";
12
+ import { logger } from "./utils/logger.js";
13
+ import routes from "./routes.js";
14
+
15
+ export const app = express();
16
+
17
+ app.set("trust proxy", 1);
18
+
19
+ app.use(
20
+ cors({
21
+ origin: env.CORS_ORIGIN,
22
+ credentials: true,
23
+ methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
24
+ allowedHeaders: ["Content-Type", "Authorization"],
25
+ }),
26
+ );
27
+
28
+ app.use(express.json({ limit: "10mb" }));
29
+ app.use(express.urlencoded({ extended: true, limit: "10mb" }));
30
+
31
+ app.use((req: Request, res: Response, next: NextFunction) => {
32
+ req.setTimeout(env.REQUEST_TIMEOUT);
33
+ res.setTimeout(env.REQUEST_TIMEOUT);
34
+ next();
35
+ });
36
+
37
+ app.use(requestLogger);
38
+
39
+ app.use("/api", routes);
40
+
41
+ app.get(
42
+ "/",
43
+ asyncHandler(async (_req: Request, res: Response) => {
44
+ sendSuccess(
45
+ res,
46
+ {
47
+ message: "Welcome to Charcole API",
48
+ version: "2.0.0",
49
+ environment: env.NODE_ENV,
50
+ },
51
+ 200,
52
+ "API is online",
53
+ );
54
+ }),
55
+ );
56
+
57
+ app.use((req: Request) => {
58
+ throw new NotFoundError(`${req.method} ${req.path}`, {
59
+ method: req.method,
60
+ path: req.path,
61
+ });
62
+ });
63
+
64
+ app.use(errorHandler);
65
+
66
+ logger.info("Express app configured successfully");
@@ -0,0 +1,20 @@
1
+ export const HTTP_STATUS = {
2
+ OK: 200,
3
+ CREATED: 201,
4
+ BAD_REQUEST: 400,
5
+ UNAUTHORIZED: 401,
6
+ FORBIDDEN: 403,
7
+ NOT_FOUND: 404,
8
+ CONFLICT: 409,
9
+ UNPROCESSABLE_ENTITY: 422,
10
+ INTERNAL_SERVER_ERROR: 500,
11
+ SERVICE_UNAVAILABLE: 503,
12
+ };
13
+
14
+ export const ERROR_MESSAGES = {
15
+ VALIDATION_ERROR: "Validation failed",
16
+ NOT_FOUND: "Resource not found",
17
+ UNAUTHORIZED: "Unauthorized",
18
+ SERVER_ERROR: "Internal server error",
19
+ BAD_REQUEST: "Bad request",
20
+ };
@@ -0,0 +1,27 @@
1
+ export const HTTP_STATUS = {
2
+ OK: 200,
3
+ CREATED: 201,
4
+ BAD_REQUEST: 400,
5
+ UNAUTHORIZED: 401,
6
+ FORBIDDEN: 403,
7
+ NOT_FOUND: 404,
8
+ CONFLICT: 409,
9
+ UNPROCESSABLE_ENTITY: 422,
10
+ INTERNAL_SERVER_ERROR: 500,
11
+ SERVICE_UNAVAILABLE: 503,
12
+ } as const;
13
+
14
+ export type HttpStatus = typeof HTTP_STATUS;
15
+
16
+ export const ERROR_MESSAGES = {
17
+ VALIDATION_ERROR: "Validation failed",
18
+ NOT_FOUND: "Resource not found",
19
+ UNAUTHORIZED: "Unauthorized",
20
+ SERVER_ERROR: "Internal server error",
21
+ BAD_REQUEST: "Bad request",
22
+ } as const;
23
+
24
+ export type ErrorMessages = typeof ERROR_MESSAGES;
25
+
26
+ export type HttpStatusCode = (typeof HTTP_STATUS)[keyof typeof HTTP_STATUS];
27
+ export type ErrorMessage = (typeof ERROR_MESSAGES)[keyof typeof ERROR_MESSAGES];
@@ -0,0 +1,26 @@
1
+ import { z } from "zod";
2
+
3
+ const envSchema = z.object({
4
+ NODE_ENV: z
5
+ .enum(["development", "production", "test"])
6
+ .default("development"),
7
+ PORT: z.coerce.number().default(3000),
8
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
9
+ CORS_ORIGIN: z.string().default("*"),
10
+ REQUEST_TIMEOUT: z.coerce.number().default(30000),
11
+ });
12
+
13
+ const parseEnv = () => {
14
+ try {
15
+ return envSchema.parse(process.env);
16
+ } catch (error) {
17
+ console.error("❌ Invalid environment variables:", error.errors);
18
+ process.exit(1);
19
+ }
20
+ };
21
+
22
+ export const env = parseEnv();
23
+
24
+ export const isDevelopment = env.NODE_ENV === "development";
25
+ export const isProduction = env.NODE_ENV === "production";
26
+ export const isTest = env.NODE_ENV === "test";
@@ -0,0 +1,40 @@
1
+ import { z } from "zod";
2
+
3
+ const envSchema = z.object({
4
+ NODE_ENV: z
5
+ .enum(["development", "production", "test"])
6
+ .default("development"),
7
+ PORT: z.coerce.number().default(3000),
8
+ LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
9
+ CORS_ORIGIN: z.string().default("*"),
10
+ REQUEST_TIMEOUT: z.coerce.number().default(30000),
11
+ });
12
+
13
+ type EnvSchema = z.infer<typeof envSchema>;
14
+
15
+ const parseEnv = (): EnvSchema => {
16
+ try {
17
+ return envSchema.parse(process.env);
18
+ } catch (error) {
19
+ if (error instanceof z.ZodError) {
20
+ console.error("❌ Invalid environment variables:");
21
+ error.errors.forEach((err) => {
22
+ console.error(` - ${err.path.join(".")}: ${err.message}`);
23
+ });
24
+ } else {
25
+ console.error("❌ Failed to parse environment variables:", error);
26
+ }
27
+ process.exit(1);
28
+ }
29
+ };
30
+
31
+ const parsedEnv = parseEnv();
32
+
33
+ export const env = {
34
+ ...parsedEnv,
35
+ isDevelopment: parsedEnv.NODE_ENV === "development",
36
+ isProduction: parsedEnv.NODE_ENV === "production",
37
+ isTest: parsedEnv.NODE_ENV === "test",
38
+ } as const;
39
+
40
+ export type Env = typeof env;
@@ -0,0 +1,180 @@
1
+ import { ZodError } from "zod";
2
+ import { HTTP_STATUS, ERROR_MESSAGES } from "../config/constants.js";
3
+ import { logger } from "../utils/logger.js";
4
+ import {
5
+ AppError,
6
+ ValidationError,
7
+ InternalServerError,
8
+ } from "../utils/AppError.js";
9
+ import { env } from "../config/env.js";
10
+
11
+ /**
12
+ * Normalize different error types to AppError
13
+ */
14
+ const normalizeError = (err) => {
15
+ // Already an AppError
16
+ if (err instanceof AppError) {
17
+ return err;
18
+ }
19
+
20
+ // Zod validation error
21
+ if (err instanceof ZodError) {
22
+ const errors = err.errors.map((e) => ({
23
+ field: e.path.join("."),
24
+ message: e.message,
25
+ code: e.code,
26
+ }));
27
+ return new ValidationError(ERROR_MESSAGES.VALIDATION_ERROR, errors);
28
+ }
29
+
30
+ // Syntax errors (programmer error)
31
+ if (err instanceof SyntaxError) {
32
+ return new InternalServerError("Syntax error in application code", err, {
33
+ type: "SyntaxError",
34
+ });
35
+ }
36
+
37
+ // Type errors (programmer error)
38
+ if (err instanceof TypeError) {
39
+ return new InternalServerError("Type error in application", err, {
40
+ type: "TypeError",
41
+ });
42
+ }
43
+
44
+ // Reference errors (programmer error)
45
+ if (err instanceof ReferenceError) {
46
+ return new InternalServerError("Reference error in application", err, {
47
+ type: "ReferenceError",
48
+ });
49
+ }
50
+
51
+ // Range errors
52
+ if (err instanceof RangeError) {
53
+ return new InternalServerError("Range error in application", err, {
54
+ type: "RangeError",
55
+ });
56
+ }
57
+
58
+ // Generic error (unknown)
59
+ return new InternalServerError(
60
+ err.message || ERROR_MESSAGES.SERVER_ERROR,
61
+ err,
62
+ { type: "UnknownError" },
63
+ );
64
+ };
65
+
66
+ /**
67
+ * Log error based on type (operational vs programmer)
68
+ */
69
+ const logError = (appError, req) => {
70
+ const errorDetails = {
71
+ type: appError.isOperational ? "OPERATIONAL" : "PROGRAMMER",
72
+ code: appError.code,
73
+ message: appError.message,
74
+ statusCode: appError.statusCode,
75
+ method: req.method,
76
+ path: req.path,
77
+ query: req.query,
78
+ ip: req.ip,
79
+ userAgent: req.get("user-agent"),
80
+ };
81
+
82
+ // Operational errors: normal logging
83
+ if (appError.isOperational) {
84
+ logger.warn(`Operational Error: ${appError.code}`, errorDetails);
85
+ } else {
86
+ // Programmer errors: detailed logging with stack
87
+ logger.error(
88
+ `Programmer Error: ${appError.code}`,
89
+ errorDetails,
90
+ appError.stack,
91
+ );
92
+ }
93
+
94
+ // Log validation errors separately
95
+ if (appError instanceof ValidationError && appError.errors) {
96
+ logger.debug("Validation errors", { errors: appError.errors });
97
+ }
98
+
99
+ // Log cause if present
100
+ if (appError.cause) {
101
+ logger.debug("Error cause", { cause: appError.cause.message });
102
+ }
103
+ };
104
+
105
+ /**
106
+ * Send error response
107
+ */
108
+ const sendErrorResponse = (res, appError) => {
109
+ const statusCode = appError.statusCode || HTTP_STATUS.INTERNAL_SERVER_ERROR;
110
+
111
+ // In production, hide internal details for programmer errors
112
+ if (!appError.isOperational && env.isProduction) {
113
+ return res.status(statusCode).json({
114
+ success: false,
115
+ message: ERROR_MESSAGES.SERVER_ERROR,
116
+ code: "INTERNAL_SERVER_ERROR",
117
+ timestamp: new Date().toISOString(),
118
+ });
119
+ }
120
+
121
+ // Return detailed error in development
122
+ const response = appError.toJSON
123
+ ? appError.toJSON()
124
+ : {
125
+ success: false,
126
+ message: appError.message,
127
+ code: appError.code,
128
+ statusCode,
129
+ timestamp: new Date().toISOString(),
130
+ };
131
+
132
+ return res.status(statusCode).json(response);
133
+ };
134
+
135
+ /**
136
+ * Global Error Handler Middleware
137
+ *
138
+ * This middleware catches all errors and provides a unified way to handle them.
139
+ * MUST be the last middleware in the app.
140
+ *
141
+ * Features:
142
+ * - Distinguishes between operational and programmer errors
143
+ * - Logs errors with full context
144
+ * - Hides sensitive info in production
145
+ * - Formats JSON responses consistently
146
+ */
147
+ export const errorHandler = (err, req, res, next) => {
148
+ // Normalize the error
149
+ const appError = normalizeError(err);
150
+
151
+ // Log the error
152
+ logError(appError, req);
153
+
154
+ // Send response
155
+ sendErrorResponse(res, appError);
156
+ };
157
+
158
+ /**
159
+ * Async error wrapper
160
+ * Wrap async route handlers to catch errors and pass to middleware
161
+ *
162
+ * Example:
163
+ * router.get('/users/:id', asyncHandler(getUserHandler))
164
+ */
165
+ export const asyncHandler = (fn) => {
166
+ return (req, res, next) => {
167
+ return Promise.resolve(fn(req, res, next)).catch(next);
168
+ };
169
+ };
170
+
171
+ export {
172
+ AppError,
173
+ ValidationError,
174
+ InternalServerError,
175
+ AuthenticationError,
176
+ AuthorizationError,
177
+ NotFoundError,
178
+ ConflictError,
179
+ BadRequestError,
180
+ } from "../utils/AppError.js";
@@ -0,0 +1,209 @@
1
+ import { ZodError } from "zod";
2
+ import { HTTP_STATUS, ERROR_MESSAGES } from "../config/constants.js";
3
+ import { logger } from "../utils/logger.js";
4
+ import {
5
+ AppError,
6
+ ValidationError,
7
+ InternalServerError,
8
+ AuthenticationError,
9
+ AuthorizationError,
10
+ NotFoundError,
11
+ ConflictError,
12
+ BadRequestError,
13
+ } from "../utils/AppError.js";
14
+ import { env } from "../config/env.js";
15
+ import { Request, Response, NextFunction, RequestHandler } from "express";
16
+
17
+ const normalizeError = (err: unknown): AppError => {
18
+ if (err instanceof AppError) {
19
+ return err;
20
+ }
21
+
22
+ if (err instanceof ZodError) {
23
+ const errors = err.errors.map((e) => ({
24
+ field: e.path.join("."),
25
+ message: e.message,
26
+ code: e.code,
27
+ }));
28
+ return new ValidationError(ERROR_MESSAGES.VALIDATION_ERROR, errors);
29
+ }
30
+
31
+ if (err instanceof Error) {
32
+ if (err instanceof SyntaxError) {
33
+ return new InternalServerError("Syntax error in application code", err, {
34
+ type: "SyntaxError",
35
+ });
36
+ }
37
+
38
+ if (err instanceof TypeError) {
39
+ return new InternalServerError("Type error in application", err, {
40
+ type: "TypeError",
41
+ });
42
+ }
43
+
44
+ if (err instanceof ReferenceError) {
45
+ return new InternalServerError("Reference error in application", err, {
46
+ type: "ReferenceError",
47
+ });
48
+ }
49
+
50
+ if (err instanceof RangeError) {
51
+ return new InternalServerError("Range error in application", err, {
52
+ type: "RangeError",
53
+ });
54
+ }
55
+
56
+ return new InternalServerError(
57
+ err.message || ERROR_MESSAGES.SERVER_ERROR,
58
+ err,
59
+ { type: "UnknownError" },
60
+ );
61
+ }
62
+
63
+ const errorMessage =
64
+ typeof err === "string"
65
+ ? err
66
+ : err &&
67
+ typeof err === "object" &&
68
+ "message" in err &&
69
+ typeof err.message === "string"
70
+ ? err.message
71
+ : ERROR_MESSAGES.SERVER_ERROR;
72
+
73
+ return new InternalServerError(
74
+ errorMessage,
75
+ err instanceof Error ? err : new Error(String(err)),
76
+ { type: "UnknownError" },
77
+ );
78
+ };
79
+
80
+ const logError = (appError: AppError, req: Request): void => {
81
+ const errorDetails = {
82
+ type: appError.isOperational ? "OPERATIONAL" : "PROGRAMMER",
83
+ code: appError.code,
84
+ message: appError.message,
85
+ statusCode: appError.statusCode,
86
+ method: req.method,
87
+ path: req.path,
88
+ query: req.query,
89
+ ip: req.ip,
90
+ userAgent: req.get("user-agent"),
91
+ };
92
+
93
+ if (appError.isOperational) {
94
+ logger.warn(`Operational Error: ${appError.code}`, errorDetails);
95
+ } else {
96
+ logger.error(
97
+ `Programmer Error: ${appError.code}`,
98
+ errorDetails,
99
+ appError.stack,
100
+ );
101
+ }
102
+
103
+ if (
104
+ appError instanceof ValidationError &&
105
+ (appError as ValidationError).errors
106
+ ) {
107
+ const validationError = appError as ValidationError;
108
+ logger.debug("Validation errors", { errors: validationError.errors });
109
+ }
110
+
111
+ if (appError.cause) {
112
+ const causeMessage =
113
+ appError.cause instanceof Error
114
+ ? appError.cause.message
115
+ : String(appError.cause);
116
+ logger.debug("Error cause", { cause: causeMessage });
117
+ }
118
+ };
119
+
120
+ const sendErrorResponse = (res: Response, appError: AppError): void => {
121
+ const statusCode = appError.statusCode || HTTP_STATUS.INTERNAL_SERVER_ERROR;
122
+
123
+ if (!appError.isOperational && env.isProduction) {
124
+ res.status(statusCode).json({
125
+ success: false,
126
+ message: ERROR_MESSAGES.SERVER_ERROR,
127
+ code: "INTERNAL_SERVER_ERROR",
128
+ timestamp: new Date().toISOString(),
129
+ });
130
+ return;
131
+ }
132
+
133
+ const response =
134
+ (appError as any).toJSON && typeof (appError as any).toJSON === "function"
135
+ ? (appError as any).toJSON()
136
+ : {
137
+ success: false,
138
+ message: appError.message,
139
+ code: appError.code,
140
+ statusCode,
141
+ timestamp: new Date().toISOString(),
142
+ };
143
+
144
+ res.status(statusCode).json(response);
145
+ };
146
+
147
+ /**
148
+ * Global Error Handler Middleware
149
+ *
150
+ * This middleware catches all errors and provides a unified way to handle them.
151
+ * MUST be the last middleware in the app.
152
+ *
153
+ * Features:
154
+ * - Distinguishes between operational and programmer errors
155
+ * - Logs errors with full context
156
+ * - Hides sensitive info in production
157
+ * - Formats JSON responses consistently
158
+ */
159
+ export const errorHandler = (
160
+ err: unknown,
161
+ req: Request,
162
+ res: Response,
163
+ next: NextFunction,
164
+ ): void => {
165
+ const appError = normalizeError(err);
166
+
167
+ logError(appError, req);
168
+
169
+ sendErrorResponse(res, appError);
170
+ };
171
+
172
+ /**
173
+ * Async error wrapper
174
+ * Wrap async route handlers to catch errors and pass to middleware
175
+ *
176
+ * Example:
177
+ * router.get('/users/:id', asyncHandler(getUserHandler))
178
+ */
179
+ export const asyncHandler = (fn: RequestHandler): RequestHandler => {
180
+ return (req: Request, res: Response, next: NextFunction): any => {
181
+ try {
182
+ const result = fn(req, res, next);
183
+
184
+ if (
185
+ result &&
186
+ typeof result === "object" &&
187
+ "then" in result &&
188
+ typeof result.then === "function"
189
+ ) {
190
+ return (result as Promise<any>).catch(next);
191
+ }
192
+
193
+ return result;
194
+ } catch (err) {
195
+ return next(err);
196
+ }
197
+ };
198
+ };
199
+
200
+ export {
201
+ AppError,
202
+ ValidationError,
203
+ InternalServerError,
204
+ AuthenticationError,
205
+ AuthorizationError,
206
+ NotFoundError,
207
+ ConflictError,
208
+ BadRequestError,
209
+ };