-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathErrorMiddleware.js
76 lines (59 loc) · 1.73 KB
/
ErrorMiddleware.js
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
const _some = require('lodash.some');
const _assignIn = require('lodash.assignin');
module.exports = function (
SpurErrors,
Logger,
HtmlErrorRender,
BaseMiddleware
) {
class ErrorMiddleware extends BaseMiddleware {
configure(app) {
super.configure(app);
this.EXCLUDE_STATUSCODE_FROM_LOGS = [404];
this.app.use(this.throwNotFoundError);
this.app.use(this.middleware.bind(this));
}
throwNotFoundError(req, res, next) {
next(SpurErrors.NotFoundError.create('Not Found'));
}
middleware(err, req, res, next) {
if (!err.statusCode) {
err = SpurErrors.InternalServerError.create(err.message, err);
}
this.appendRequestData(err, req);
this.logErrorStack(err);
res.status(err.statusCode);
res.format({
text: () => this.sendTextResponse(err, req, res),
html: () => this.sendHtmlResponse(err, req, res),
json: () => this.sendJsonResponse(err, req, res)
});
next();
}
logErrorStack(err) {
const statusCode = err.statusCode || 0;
const checkStatus = (status) => status === statusCode;
if (!_some(this.EXCLUDE_STATUSCODE_FROM_LOGS, checkStatus)) {
Logger.error(err, '\n', err.stack, '\n', (err.data || ''));
}
}
appendRequestData(err, req) {
if (err.data == null) {
err.data = {};
}
err.data = _assignIn(err.data, {
url: req.url
});
}
sendTextResponse(err, req, res) {
res.send(err.message);
}
sendHtmlResponse(err, req, res) {
HtmlErrorRender.render(err, req, res);
}
sendJsonResponse(err, req, res) {
res.json({ error: err.message, data: err.data });
}
}
return new ErrorMiddleware();
};