Node.js异常处理

时间:2024-10-16 15:06:08
var log4js = require('log4js');
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'd:/logs/my-app.log', category: 'my-app' }
]
});
var log = log4js.getLogger('my-app');
log.setLevel('INFO');
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
log.error("==========404===============");
var err = new Error('Not Found');
err.status = 404;
next(err);
}); /// error handlers // development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
log.error("开发环境==========="+err);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
} // production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
log.error("生产环境==========="+err);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
/*process.on('uncaughtException', function(err) {
log.error("uncaughtException==========="+err);
});*/