-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy patherrorHandler.js
More file actions
228 lines (199 loc) · 6.23 KB
/
errorHandler.js
File metadata and controls
228 lines (199 loc) · 6.23 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
217
218
219
220
221
222
223
224
225
226
227
228
/**
* Error handling utilities for graceful server error management
* Catches errors in async routes and emits Socket.IO events for UI alerting
*/
import { EventEmitter } from 'events';
// Global error event emitter for broadcasting errors
export const errorEvents = new EventEmitter();
/**
* Enhanced error object with metadata
*/
export class ServerError extends Error {
constructor(message, options = {}) {
super(message);
this.name = 'ServerError';
this.status = options.status || 500;
this.code = options.code || 'INTERNAL_ERROR';
this.timestamp = Date.now();
this.context = options.context || {};
this.severity = options.severity || 'error'; // error, critical, warning
this.canAutoFix = options.canAutoFix || false;
}
}
/**
* Wrap async route handlers to catch errors and emit Socket.IO events
* Also sends error response to client
*/
export function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch((err) => {
const io = req.app.get('io');
const error = normalizeError(err);
// Log the error (skip stack traces for upstream platform issues)
const logMsg = `❌ Route error: ${error.message}`;
if (error.code === 'PLATFORM_UNAVAILABLE') {
console.warn(`⚠️ Platform unavailable: ${error.message}`);
} else if (error.status >= 500) {
console.error(logMsg, error.stack ? error.stack : '');
} else {
const details = error.context?.details;
console.error(details ? `${logMsg}: ${JSON.stringify(details)}` : logMsg);
}
// Emit Socket.IO event for UI notification
if (io) {
emitErrorEvent(io, error);
}
// Send error response
return res.status(error.status).json({
error: error.message,
code: error.code,
timestamp: error.timestamp,
...(error.context && Object.keys(error.context).length > 0 && { context: error.context })
});
});
};
}
/**
* Normalize different error types to ServerError
*/
export function normalizeError(err) {
if (err instanceof ServerError) {
return err;
}
if (err instanceof Error) {
const status = err.status || 500;
const code = err.code || getErrorCode(status);
return new ServerError(err.message, {
status,
code,
context: { originalError: err.constructor.name }
});
}
// Handle string or other error types
return new ServerError(String(err), {
status: 500,
code: 'INTERNAL_ERROR'
});
}
/**
* Get appropriate error code from HTTP status
*/
function getErrorCode(status) {
const codeMap = {
400: 'BAD_REQUEST',
401: 'UNAUTHORIZED',
403: 'FORBIDDEN',
404: 'NOT_FOUND',
409: 'CONFLICT',
422: 'VALIDATION_ERROR',
500: 'INTERNAL_ERROR',
502: 'BAD_GATEWAY',
503: 'SERVICE_UNAVAILABLE'
};
return codeMap[status] || 'INTERNAL_ERROR';
}
/**
* Strip sensitive fields from error context before broadcasting to clients.
* Full context is still available in server-side console logs.
*/
function sanitizeContext(context) {
if (!context || typeof context !== 'object') return context;
const sensitive = ['apikey', 'token', 'secret', 'password', 'credential', 'authorization', 'bearer', 'envvars', 'secretenvvars'];
const visited = new WeakSet();
function sanitize(value) {
if (value === null || typeof value !== 'object') return value;
if (visited.has(value)) return undefined;
visited.add(value);
if (Array.isArray(value)) return value.map(sanitize).filter(v => v !== undefined);
const result = {};
for (const [key, val] of Object.entries(value)) {
if (sensitive.some(s => key.toLowerCase().includes(s))) continue;
const sanitized = sanitize(val);
if (sanitized !== undefined) result[key] = sanitized;
}
return result;
}
return sanitize(context);
}
/**
* Emit error event via Socket.IO to alert UI
*/
export function emitErrorEvent(io, error) {
errorEvents.emit('error', error);
const safeContext = sanitizeContext(error.context);
// Broadcast to all connected clients
io.emit('error:occurred', {
message: error.message,
code: error.code,
status: error.status,
severity: error.severity,
timestamp: error.timestamp,
context: safeContext,
canAutoFix: error.canAutoFix
});
// If critical, also emit to system/health channel
if (error.severity === 'critical') {
io.emit('system:critical-error', {
message: error.message,
code: error.code,
timestamp: error.timestamp,
context: safeContext
});
}
}
/**
* Middleware to handle errors with Socket.IO event emission
* Use as the last middleware before the app listens
*/
export function errorMiddleware(err, req, res, next) {
const io = req.app.get('io');
const error = normalizeError(err);
// Log the error
const logMsg = `❌ Server error: ${error.message}`;
if (error.status >= 500) {
console.error(logMsg);
if (err.stack) console.error(err.stack);
} else {
console.error(logMsg);
}
// Emit Socket.IO event
if (io) {
emitErrorEvent(io, error);
}
// Send response
res.status(error.status).json({
error: error.message,
code: error.code,
timestamp: error.timestamp
});
}
/**
* Handle unhandled promise rejections with Socket.IO broadcasting
* Should be called with the io instance
*/
export function setupProcessErrorHandlers(io) {
process.on('unhandledRejection', (reason, promise) => {
const error = normalizeError(reason);
error.severity = 'critical';
console.error(`❌ Unhandled Promise Rejection: ${error.message}`);
if (reason instanceof Error) {
console.error(reason.stack);
}
if (io) {
emitErrorEvent(io, error);
}
});
process.on('uncaughtException', (error) => {
const serverError = normalizeError(error);
serverError.severity = 'critical';
serverError.canAutoFix = true; // Could be auto-fixable
console.error(`💥 Uncaught Exception: ${serverError.message}`);
console.error(error.stack);
if (io) {
emitErrorEvent(io, serverError);
}
// Process is in undefined state after uncaught exception — must exit.
// Use a short delay to allow the socket event to flush before exiting.
setTimeout(() => process.exit(1), 100);
});
}