forked from maksrom/javascript-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorHandler.js
More file actions
114 lines (85 loc) · 2.38 KB
/
Copy patherrorHandler.js
File metadata and controls
114 lines (85 loc) · 2.38 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
'use strict';
const config = require('config');
const escapeHtml = require('escape-html');
function renderUserError(error) {
/*jshint -W040 */
this.status = error.status || 500;
var preferredType = this.accepts('html', 'json');
if (preferredType == 'json') {
this.body = error;
} else {
this.body = this.render("error", {error: error});
}
}
function renderDevError(error) {
/*jshint -W040 */
this.status = 500;
var preferredType = this.accepts('html', 'json');
if (preferredType == 'json') {
this.body = error;
} else {
var stack = (error.stack || '')
.split('\n').slice(1)
.map(function(v) {
return '<li>' + escapeHtml(v).replace(/ /g, ' ') + '</li>';
}).join('');
this.type = 'text/html; charset=utf-8';
this.body = "<html><body><h1>" + error.message + "</h1><ul>" + stack + "</ul></body></html>";
}
}
function renderError(err) {
/*jshint -W040 */
if (err.status) {
// user-level error
// this.log.error({httpError: err});
renderUserError.call(this, err);
} else {
// if error is "call stack too long", then log.error(err) is not verbose
// so I cast it to string
this.log.error(err.toString());
this.log.error(err.stack);
this.set('X-Content-Type-Options', 'nosniff');
if (process.env.NODE_ENV == 'development') {
renderDevError.call(this, err);
} else {
renderUserError.call(this, {status: 500, message: "Ошибка на стороне сервера"});
}
}
}
function renderValidationError(error) {
/*jshint -W040 */
this.status = 400;
var errors = {};
for (var field in error.errors) {
errors[field] = error.errors[field].message;
}
this.body = {
errors: errors
};
}
module.exports = function(app) {
app.use(function*(next) {
this.renderError = renderError;
this.renderValidationError = renderValidationError;
try {
yield* next;
} catch (err) {
this.renderError(err);
}
});
// this middleware handles error BEFORE ^^^
// rewrite mongoose wrong mongoose parameter -> 400 (not 500)
app.use(function* rewriteCastError(next) {
try {
yield next;
} catch (err) {
if (err.name == 'CastError') {
// malformed or absent mongoose params
if (process.env.NODE_ENV != 'development') {
this.throw(400);
}
}
throw err;
}
});
};