思路: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 = '"';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = ''';
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
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 = /\n/g
var body = escapeHtml(message)
.replace(NEWLINE_REGEXP, '<br>')
.replace(DOUBLE_SPACE_REGEXP, ' ')
return txtType == 'text' ? body : '<!DOCTYPE html>\n' +
'<html lang="en">\n' +
'<head>\n' +
'<meta charset="utf-8">\n' +
'<title>Error</title>\n' +
'</head>\n' +
'<body>\n' +
'<pre>' + body + '</pre>\n' +
'</body>\n' +
'</html>\n'
}
function sendErrCourier(msg) {
// do send message
}