如何在不使用winston终止的情况下处理Nodejs uncaughtException和unhandledRejection

How to handle Nodejs uncaughtException and unhandledRejection without termination using winston

我正在尝试找到一种方法来捕获项目中的所有错误并将它们保存到数据库和文件日志中。我已经创建了以下中间件来帮助我满足这一需求,但我使用 winston 面临的唯一问题是一旦处理了 uncaughtException 或 unhandledRejection,应用程序就会终止。温斯顿有没有办法避免这种终止。我想要的只是为了他们能被保存下来并在以后删除。

const winston = require('winston'); 

require('winston-mongodb');

module.exports = function () {
process.on('unhandledRejection', (ex) => {
    //console.error('error', ex);
    throw ex; //Find better way
});//Catching uncaught exceptions with winston. We are using both file and db.
winston.exceptions.handle([
        new winston.transports.MongoDB({
            db: 'mongodb://localhost/web_logs',
            collection: 'exceptions',
            level: 'error'
        }),
        new winston.transports.Console,
        new winston.transports.File({filename: 'web-exceptions.log'})
    ]
);};

在路由后用在express中作为

require('./middleware/exception-handler')();

它按预期运行良好,但它终止了应用程序。如何避免这种情况?

有expressjs错误处理中间件功能吗? // 在你的 index.js 或 app.js 文件中有这样的东西

`app.use(function (err, req, res, next) {
   console.error(err.stack)
   res.status(500).send('Something broke!')
 });`

winstonjs 会记录错误,但不会捕获它们,因此它会使您的应用程序崩溃