forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorHandler.js
More file actions
175 lines (155 loc) · 4.15 KB
/
Copy patherrorHandler.js
File metadata and controls
175 lines (155 loc) · 4.15 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
import logger from "../config/logger.js";
/**
* Custom Error class for API errors
*/
export class APIError extends Error {
constructor(message, statusCode = 500, isOperational = true) {
super(message);
this.statusCode = statusCode;
this.isOperational = isOperational;
this.status = `${statusCode}`.startsWith("4") ? "fail" : "error";
Error.captureStackTrace(this, this.constructor);
}
}
/**
* Handle MongoDB Cast Errors (Invalid ObjectId)
*/
const handleCastErrorDB = (err) => {
const message = `Invalid ${err.path}: ${err.value}`;
return new APIError(message, 400);
};
/**
* Handle MongoDB Duplicate Key Errors
*/
const handleDuplicateFieldsDB = (err) => {
const value = err.errmsg?.match(/(["'])(\\?.)*?\1/)[0];
const message = `Duplicate field value: ${value}. Please use another value!`;
return new APIError(message, 400);
};
/**
* Handle MongoDB Validation Errors
*/
const handleValidationErrorDB = (err) => {
const errors = Object.values(err.errors).map((el) => el.message);
const message = `Invalid input data. ${errors.join(". ")}`;
return new APIError(message, 400);
};
/**
* Handle JWT Errors
*/
const handleJWTError = () =>
new APIError("Invalid token. Please log in again!", 401);
const handleJWTExpiredError = () =>
new APIError("Your token has expired! Please log in again.", 401);
/**
* Send error response in development
*/
const sendErrorDev = (err, res) => {
logger.error("ERROR 💥", {
status: err.status,
error: err,
message: err.message,
stack: err.stack,
});
res.status(err.statusCode).json({
success: false,
status: err.status,
error: err,
message: err.message,
stack: err.stack,
});
};
/**
* Send error response in production
*/
const sendErrorProd = (err, res) => {
// Operational, trusted error: send message to client
if (err.isOperational) {
logger.error("Operational Error:", {
message: err.message,
statusCode: err.statusCode,
});
res.status(err.statusCode).json({
success: false,
status: err.status,
message: err.message,
});
}
// Programming or unknown error: don't leak error details
else {
logger.error("Programming Error 💥", {
error: err,
message: err.message,
stack: err.stack,
});
res.status(500).json({
success: false,
status: "error",
message: "Something went wrong!",
});
}
};
/**
* Global Error Handler Middleware
*/
export const errorHandler = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || "error";
if (process.env.NODE_ENV === "development") {
sendErrorDev(err, res);
} else {
let error = { ...err };
error.message = err.message;
// Handle specific error types
if (err.name === "CastError") error = handleCastErrorDB(err);
if (err.code === 11000) error = handleDuplicateFieldsDB(err);
if (err.name === "ValidationError") error = handleValidationErrorDB(err);
if (err.name === "JsonWebTokenError") error = handleJWTError();
if (err.name === "TokenExpiredError") error = handleJWTExpiredError();
sendErrorProd(error, res);
}
};
/**
* Catch async errors wrapper
*/
export const catchAsync = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
/**
* Handle 404 - Route not found
*/
export const notFound = (req, res, next) => {
const message = `Can't find ${req.originalUrl} on this server!`;
logger.warn(`404 - ${message}`);
next(new APIError(message, 404));
};
/**
* Handle unhandled promise rejections
*/
export const handleUnhandledRejection = () => {
process.on("unhandledRejection", (err) => {
logger.error("UNHANDLED REJECTION! 💥 Shutting down...");
logger.error(err.name, err.message);
process.exit(1);
});
};
/**
* Handle uncaught exceptions
*/
export const handleUncaughtException = () => {
process.on("uncaughtException", (err) => {
logger.error("UNCAUGHT EXCEPTION! 💥 Shutting down...");
logger.error(err.name, err.message);
process.exit(1);
});
};
export default {
APIError,
errorHandler,
catchAsync,
notFound,
handleUnhandledRejection,
handleUncaughtException,
};