【问题标题】:How to handle Nodejs uncaughtException and unhandledRejection without termination using winston如何使用winston在不终止的情况下处理Nodejs uncaughtException和unhandledRejection
【发布时间】:2019-01-23 13:50:27
【问题描述】:

我正在尝试找到一种方法来捕获项目中的所有错误并将它们保存到数据库以及文件日志中。我已经创建了以下中间件来帮助我满足这种需求,但我使用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')();

它按预期运行,但它终止了应用程序。如何避免?

【问题讨论】:

    标签: node.js express winston


    【解决方案1】:

    是否有 expressjs 错误处理中间件功能? // 在你的 index.js 或 app.js 文件中类似这样的内容

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

    winstonjs 记录错误,但它们没有被捕获,因此它会导致您的应用崩溃

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多