forked from mongodb/docs-sample-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorHandler.ts
More file actions
216 lines (202 loc) · 5.26 KB
/
errorHandler.ts
File metadata and controls
216 lines (202 loc) · 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* Error Handling Utilities
*
* This module provides centralized error handling for the Express application.
* It includes middleware for catching and formatting errors in a consistent way.
*/
import { Request, Response, NextFunction } from "express";
import { MongoError } from "mongodb";
import { SuccessResponse, ErrorResponse } from "../types";
/**
* Custom ValidationError class for field validation errors
*/
export class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
/**
* Global error handling middleware
*
* This middleware catches all unhandled errors and returns a consistent
* error response format. It should be the last middleware in the chain.
*
* @param err - The error that was thrown
* @param req - Express request object
* @param res - Express response object
* @param next - Express next function
*/
export function errorHandler(
err: Error,
req: Request,
res: Response,
next: NextFunction
): void {
// Log the error for debugging purposes
// In production, we recommend using a logging service
// Suppress error logging during tests to keep test output clean
if (process.env.NODE_ENV !== "test") {
console.error("Error occurred:", {
message: err.message,
stack: err.stack,
url: req.url,
method: req.method,
timestamp: new Date().toISOString(),
});
}
// Determine the appropriate HTTP status code and error message
const errorDetails = parseErrorDetails(err);
const response: ErrorResponse = createErrorResponse(
errorDetails.message,
errorDetails.code,
errorDetails.details
);
// Send the error response
res.status(errorDetails.statusCode).json(response);
}
/**
* Creates a standardized error response based on the error type
*
* @param err - The error to process
* @returns Object containing status code, message, and optional details
*/
/**
* Internal helper function to parse error details and determine HTTP status codes
*/
function parseErrorDetails(err: Error): {
message: string;
code: string;
details?: any;
statusCode: number;
} {
// MongoDB specific error handling
if (err instanceof MongoError) {
switch (err.code) {
case 11000:
return {
message: "Duplicate key error",
code: "DUPLICATE_KEY",
details: "A document with this data already exists",
statusCode: 409,
};
case 121:
// Document validation failed
return {
statusCode: 400,
message: "Document validation failed",
code: "DOCUMENT_VALIDATION_ERROR",
details: err.message,
};
default:
return {
message: "Database error",
code: "DATABASE_ERROR",
details: err.code,
statusCode: 500,
};
}
}
// Validation errors
if (err.name === "ValidationError") {
return {
message: "Validation failed",
code: "VALIDATION_ERROR",
details: err.message,
statusCode: 400,
};
}
// Default error handling
return {
message: err.message || "Internal server error",
code: "INTERNAL_ERROR",
statusCode: 500,
};
}
/**
* Async wrapper function for route handlers
*
* This function wraps async route handlers to automatically catch
* and forward any errors to the error handling middleware.
*
* Usage:
* app.get('/route', asyncHandler(async (req, res) => {
* // Your async code here
* }));
*
* @param fn - Async route handler function
* @returns Express middleware function
*/
export function asyncHandler(
fn: (req: Request, res: Response, next: NextFunction) => Promise<void>
) {
return (req: Request, res: Response, next: NextFunction) => {
try {
fn(req, res, next).catch(next);
} catch (error) {
next(error);
}
};
}
/**
* Creates a standardized success response
*
* @param data - The data to include in the response
* @param message - Optional success message
* @returns Standardized success response object
*/
export function createSuccessResponse<T>(
data: T,
message?: string
): SuccessResponse<T> {
return {
success: true,
message: message || "Operation completed successfully",
data,
timestamp: new Date().toISOString(),
};
}
/**
* Creates a standardized error response
*
* @param message - Error message
* @param code - Optional error code
* @param details - Optional error details
* @returns Standardized error response object
*/
export function createErrorResponse(
message: string,
code?: string,
details?: any
): ErrorResponse {
return {
success: false,
message,
error: {
message,
code,
details,
},
timestamp: new Date().toISOString(),
};
}
/**
* Validates that required fields are present in the request body
*
* @param body - Request body object
* @param requiredFields - Array of required field names
* @throws ValidationError if any required fields are missing
*/
export function validateRequiredFields(
body: any,
requiredFields: string[]
): void {
const missingFields = requiredFields.filter(
(field) => body[field] == null || body[field] === ""
);
if (missingFields.length > 0) {
throw new ValidationError(
`Missing required fields: ${missingFields.join(", ")}`
);
}
}