error-handler.js
1.44 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
const _ = require('lodash');
const logger = global.yoho.logger;
const cache = global.yoho.cache.master;
const helpers = global.yoho.helpers;
const appName = 'h5'; // 与H5共用
const LIMITER_IP_TIME = 3600; // 超出访问限制ip限制访问1小时
const replaceKey = '__refer__';
const checkRefer = helpers.urlFormat('/3party/check', {refer: replaceKey});
/**
* 服务器错误
* @return {[type]}
*/
exports.serverError = (err = {}, req, res, next) => { // eslint-disable-line
logger.error(`error at path: ${req.url}`);
logger.error(`${req.url},${typeof err === 'object' ? JSON.stringify(err) : err}`);
if (err.apiRisk) { // 接口风控
let remoteIp = req.yoho.clientIp;
if (_.get(req.app.locals, 'wap.open.apmrisk', false)) {
cache.setAsync(`${appName}:limit2:${remoteIp}`, 1, LIMITER_IP_TIME);
} else {
cache.setAsync(`${appName}:limiter:${remoteIp}`, 1, LIMITER_IP_TIME);
}
req.session.apiRiskValidate = true;
if (req.xhr) {
return res.status(510).json({
code: err.code,
data: {refer: checkRefer.replace(replaceKey, req.get('Referer') || '')}
});
}
return res.redirect(checkRefer.replace(replaceKey, req.protocol + '://' + req.get('host') + req.originalUrl));
}
res.status(err.code || 500);
if (req.xhr) {
return res.json({
code: err.code || 500,
message: err.message || '服务器错误'
});
}
return res.send('服务器开小差了~');
};