使用nodejs的时候,使用process.on('uncaughtException',)来监听错误信息,可以在代码出错的时候不至于退出程序。
// 容错, 就算报错也不退出程序
process.on('uncaughtException', function(err) {
console.error(' Caught exception: ' + err.stack);
});
但是我在使用express的时候发现,经常会出现代码出错了但是没有地方显示错误信息的情况,导致很多很简单的小错误都不能第一时间发现,要等到出现bug了才能排查到这些。就很蛋疼。
后面发现这些错误原来是express收集起来发送回去了,在express监听错误的回调里面打log就好了,app.js里面的
// error handler
app.use(function(err, req, res, next) {
// 在这里 打印错误log
console.error('Err:' ,err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});