error-handler.js 1.45 KB
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
  err = err || {};

  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('服务器开小差了~');
};