Blame view

doraemon/middleware/error-handler.js 1.45 KB
yyq authored
1
const _ = require('lodash');
陈峰 authored
2
const logger = global.yoho.logger;
yyq authored
3 4 5 6 7 8 9 10
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});
陈峰 authored
11 12 13 14 15

/**
 * 服务器错误
 * @return {[type]}
 */
yyq authored
16 17
exports.serverError = (err, req, res, next) => { // eslint-disable-line
  err = err || {};
陈峰 authored
18 19 20
  logger.error(`error at path: ${req.url}`);
  logger.error(`${req.url},${typeof err === 'object' ? JSON.stringify(err) : err}`);
yyq authored
21
yyq authored
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  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));
  }
陈峰 authored
43 44 45 46
  res.status(err.code || 500);

  if (req.xhr) {
    return res.json({
yyq authored
47 48
      code: err.code || 500,
      message: err.message || '服务器错误'
陈峰 authored
49 50 51 52 53
    });
  }

  return res.send('服务器开小差了~');
};