返回列表

NodeJS和Express下的全局异常捕获处理

默认分类 2018/08/08 07:47

思路:NodeJS和Express下的全局异常捕获后发信息通知开发人员

  // 注:异常处理一
  app.use(function (err, req, res, next) {
    console.error(err.stack)
    var body = createHtmlDocument(err.stack)
    res.end(body, 'utf8')

    sendErrCourier(err.stack)
  })
  app.listen(app.get('port'), function () {
    console.log('listening port ' + app.get('port'))
  })
  // 注:异常处理二
  process.on('uncaughtException', function (err) {
    console.log(err.stack)
    sendErrCourier(err.stack)
  })
  // 注:异常处理三
  process.on('unhandledRejection', (reason, p) => {
    console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
    sendErrCourier(reason)
  })
})
function escapeHtml(string) {
  var str = '' + string;
  var match = /["'&<>]/.exec(str);
  if (!match) {
    return str;
  }
  var escape;
  var html = '';
  var index = 0;
  var lastIndex = 0;
  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34: // "
        escape = '&quot;';
        break;
      case 38: // &
        escape = '&amp;';
        break;
      case 39: // '
        escape = '&#39;';
        break;
      case 60: // <
        escape = '&lt;';
        break;
      case 62: // >
        escape = '&gt;';
        break;
      default:
        continue;
    }
    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }
    lastIndex = index + 1;
    html += escape;
  }
  return lastIndex !== index ?
    html + str.substring(lastIndex, index) :
    html;
}
function createHtmlDocument(message, txtType) {
  var DOUBLE_SPACE_REGEXP = /\x20{2}/g
  var NEWLINE_REGEXP = /

/g var body = escapeHtml(message) .replace(NEWLINE_REGEXP, '
') .replace(DOUBLE_SPACE_REGEXP, '  ') return txtType == 'text' ? body : ' ' + ' ' + ' ' + ' ' + 'Error ' + ' ' + ' ' + '

' + body + '

' + ' ' + ' ' } function sendErrCourier(msg) { // do send message }