forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error-handlers.js
45 lines (41 loc) · 1.19 KB
/
error-handlers.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
import errorHanlder from 'errorhandler';
import accepts from 'accepts';
export default function prodErrorHandler() {
if (process.env.NODE_ENV === 'development') {
return errorHanlder({ log: true });
}
// error handling in production.
// disabling eslint due to express parity rules for error handlers
return function(err, req, res, next) { // eslint-disable-line
// respect err.status
if (err.status) {
res.statusCode = err.status;
}
// default status code to 500
if (res.statusCode < 400) {
res.statusCode = 500;
}
// parse res type
var accept = accepts(req);
var type = accept.type('html', 'json', 'text');
var message = 'Oops! Something went wrong. Please try again later';
if (type === 'html') {
if (typeof req.flash === 'function') {
req.flash('errors', {
msg: message
});
}
return res.redirect('/');
// json
} else if (type === 'json') {
res.setHeader('Content-Type', 'application/json');
return res.send({
message: message
});
// plain text
} else {
res.setHeader('Content-Type', 'text/plain');
return res.send(message);
}
};
}