error-handler.js
1.75 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
/**
* error处理
* @author: leo<qi.li@yoho.cn>
* @date: 2017/06/23
*/
const _ = require('lodash');
const logger = global.yoho.logger;
const sender = global.yoho.apmSender;
const hostname = require('os').hostname();
const serverError = (err, req, res, next) => { // eslint-disable-line
logger.error(err);
let code = 500, msg = '服务器错误!';
if (err.code && typeof err.code === 'number' && err.code !== 500 && err.message && !/_ERROR/.test(err.message)) {
code = err.code;
msg = err.message;
}
if (req.isApmReport && !err.apiError) {
try {
sender.addMessage({
measurement: 'error-report',
tags: {
app: global.yoho.config.appName, // 应用名称
hostname,
type: 'server',
route: `[${req.method}]${req.route && req.route.path}`, // 请求路由
reqID: req.reqID || '',
code: err.code || 500,
url: encodeURIComponent(req.originalUrl),
ip: _.get(req, 'yoho.clientIp', '')
},
fields: {
message: err.message,
stack: err.stack,
useragent: req && req.get('user-agent')
}
});
} catch(e) {} // eslint-disable-line
}
return res.status(code).json({
code: code,
message: msg
});
};
const notFound = (req, res) => {
res.status(404);
if (req.xhr) {
return res.json({
code: 404,
message: '请求路径不存在'
});
}
res.render('error/404', {
layout: false
});
};
module.exports = {
notFound,
serverError
};