error-handler.js
8.13 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
* express-error-handler
*
* A graceful error handler for Express
* applications.
*
* Copyright (C) 2013 Eric Elliott
*
* Written for
* "Programming JavaScript Applications"
* (O'Reilly)
*
* MIT License
**/
'use strict';
var mixIn = require('mout/object/mixIn'),
createObject = require('mout/lang/createObject'),
path = require('path'),
fs = require('fs'),
statusCodes = require('http').STATUS_CODES,
/**
* Return true if the error status represents
* a client error that should not trigger a
* restart.
*
* @param {number} status
* @return {boolean}
*/
isClientError = function isClientError(status) {
return (status >= 400 && status <= 499);
},
/**
* Attempt a graceful shutdown, and then time
* out if the connections fail to drain in time.
*
* @param {object} o options
* @param {object} o.server server object
* @param {object} o.timeout timeout in ms
* @param {function} exit - force kill function
*/
close = function close(o, exit) {
// We need to kill the server process so
// the app can repair itself. Your process
// should be monitored in production and
// restarted when it shuts down.
//
// That can be accomplished with modules
// like forever, forky, etc...
//
// First, try a graceful shutdown:
if (o.server && typeof o.server.close ===
'function') {
try {
o.server.close(function () {
process.exit(o.exitStatus);
});
}
finally {
process.exit(o.exitStatus);
}
}
// Just in case the server.close() callback
// never fires, this will wait for a timeout
// and then terminate. Users can override
// this function by passing options.shutdown:
exit(o);
},
/**
* Take an error status and return a route that
* sends an error with the appropriate status
* and message to an error handler via
* `next(err)`.
*
* @param {number} status
* @param {string} message
* @return {function} Express route handler
*/
httpError = function httpError (status, message) {
var err = new Error();
err.status = status;
err.message = message ||
statusCodes[status] ||
'Internal server error';
return function httpErr(req, res, next) {
next(err);
};
},
sendFile = function sendFile (staticFile, res) {
var filePath = path.resolve(staticFile),
stream = fs.createReadStream(filePath);
stream.pipe(res);
},
send = function send(statusCode, err, res, o) {
var body = {
status: statusCode,
message: err.message ||
statusCodes[statusCode]
};
body = (o.serializer) ?
o.serializer(createObject(err, body)) :
body;
res.status(statusCode);
res.send(body);
},
defaults = {
handlers: {},
views: {},
static: {},
timeout: 3 * 1000,
exitStatus: 1,
server: undefined,
shutdown: undefined,
serializer: undefined,
framework: 'express'
},
createHandler;
/**
* A graceful error handler for Express
* applications.
*
* @param {object} [options]
*
* @param {object} [options.handlers] Custom
* handlers for specific status codes.
*
* @param {object} [options.views] View files to
* render in response to specific status
* codes. Specify a default with
* options.views.default.
*
* @param {object} [options.static] Static files
* to send in response to specific status
* codes. Specify a default with
* options.static.default.
*
* @param {number} [options.timeout] Delay
* between the graceful shutdown
* attempt and the forced shutdown
* timeout.
*
* @param {number} [options.exitStatus] Custom
* process exit status code.
*
* @param {object} [options.server] The app server
* object for graceful shutdowns.
*
* @param {function} [options.shutdown] An
* alternative shutdown function if the
* graceful shutdown fails.
*
* @param {function} serializer A function to
* customize the JSON error object.
* Usage: serializer(err) return errObj
*
* @param {function} framework Either 'express'
* (default) or 'restify'.
*
* @return {function} errorHandler Express error
* handling middleware.
*/
createHandler = function createHandler(options) {
var o = mixIn({}, defaults, options),
/**
* In case of an error, wait for a timer to
* elapse, and then terminate.
* @param {object} options
* @param {number} o.exitStatus
* @param {number} o.timeout
*/
exit = o.shutdown || function exit(o){
// Give the app time for graceful shutdown.
setTimeout(function () {
process.exit(o.exitStatus);
}, o.timeout);
},
express = o.framework === 'express',
restify = o.framework === 'restify',
errorHandler;
/**
* Express error handler to handle any
* uncaught express errors. For error logging,
* see bunyan-request-logger.
*
* @param {object} err
* @param {object} req
* @param {object} res
* @param {function} next
*/
errorHandler = function errorHandler(err, req,
res, next) {
var defaultView = o.views['default'],
defaultStatic = o.static['default'],
status = err && err.status ||
res && res.statusCode,
handler = o.handlers[status],
view = o.views[status],
staticFile = o.static[status],
renderDefault = function
renderDefault(statusCode) {
res.statusCode = statusCode;
if (defaultView) {
return res.render(defaultView, err);
}
if (defaultStatic) {
return sendFile(defaultStatic, res);
}
if (restify) {
send(statusCode, err, res, o);
}
if (express) {
return res.format({
json: function () {
send(statusCode, err, res, {
serializer: o.serializer || function (o) {
return o;
}
});
},
text: function () {
send(statusCode, err, res, {
serializer: function (o) {
return o.message;
}
});
},
html: function () {
send(statusCode, err, res, {
serializer: function (o) {
return o.message;
}
});
}
});
}
},
resumeOrClose = function
resumeOrClose(status) {
if (!isClientError(status)) {
return close(o, exit);
}
};
if (!res) {
return resumeOrClose(status);
}
// If there's a custom handler defined,
// use it and return.
if (typeof handler === 'function') {
handler(err, req, res, next);
return resumeOrClose(status);
}
// If there's a custom view defined,
// render it.
if (view) {
res.render(view, err);
return resumeOrClose(status);
}
// If there's a custom static file defined,
// render it.
if (staticFile) {
sendFile(staticFile, res);
return resumeOrClose(status);
}
// If the error is user generated, send
// a helpful error message, and don't shut
// down.
//
// If we shutdown on user errors,
// attackers can send malformed requests
// for the purpose of creating a Denial
// Of Service (DOS) attack.
if (isClientError(status)) {
return renderDefault(status);
}
// For all other errors, deliver a 500
// error and shut down.
renderDefault(500);
close(o, exit);
};
if (express) {
return errorHandler;
}
if (restify) {
return function (req, res, route, err) {
return errorHandler(err, req, res);
};
}
};
createHandler.isClientError = isClientError;
createHandler.clientError = function () {
var args = [].slice.call(arguments);
console.log('WARNING: .clientError() is ' +
'deprecated. Use isClientError() instead.');
return this.isClientError.apply(this, args);
};
// HTTP error generating route.
createHandler.httpError = httpError;
module.exports = createHandler;