【问题标题】:how do I catch error in try catch by using winston in entire application?如何在整个应用程序中使用 winston 来捕获 try catch 中的错误?
【发布时间】:2019-12-24 07:56:13
【问题描述】:

winston.js


var options = {
    file: {
        level: 'info',
        filename: `./app.log`,
        handleExceptions: true,
        json: true,
        colorize: false,
        timestamp:true
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
        timestamp:true
    },
};

// var logger = {}


const logger = new winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exceptionHandlers: [
        new winston.transports.File(options.file)
      ], 
    exitOnError: false, // do not exit on handled exceptions
});

logger.stream = {
    write: function(message, encoding) {
      // use the 'info' log level so the output will be picked up by both transports (file and console)
      logger.info(message);
      return;
    },
  };

  process.on('uncaughtException', function (err) {
      console.log('err',err)
    logger.error('uncaughtException', { message : err.message, stack : err.stack }); // logging with MetaData
    // process.exit(1); // exit with failure
});

process.on('unhandledRejection', (err, promise) => {
    logger.error('uncaughtException', { message : err.message, stack : err.stack }); // logging })
});

module.exports = logger;

app.js

app.get('/data',async(req,res)=>{
    try {
        let result = await config.data(req);
        console.log(result)
        res.status(200).json({
            code:200,
            message:'Success',
            data:result
        })
    } catch (error) {
        console.log(error.message)
    }
})

这只处理promise返回错误和uncaughtException错误。

我不想将logger.error() 放在每个 try catch 块中。

config.data() 不是函数。我想在整个应用程序中自动捕获这个错误。

请有人帮我解决这个问题。我被困在项目的这一点上。

【问题讨论】:

    标签: node.js winston


    【解决方案1】:

    通常 nodeJS 应用程序会定义一个错误处理程序中间件,用于捕获所有异常、记录它们并返回有效响应。

    app.get('/data', ...);
    app.post('/data', ...);
    ...
    // global error handler goes here
    app.use(function (err, req, res, next) {
      logger.error(err)
      res.status(500).send('Something broke!')
    })
    

    这个中间件通常被定义为最后一个应用处理程序。

    【讨论】:

    • 谢谢。但我想在整个应用程序的 try catch 块中捕获错误。
    【解决方案2】:

    试试这个,

    app.get('/data', async (req, res, next) => {
        try {
            let result = await config.data(req);
            console.log(result)
            res.status(200).json({
                code: 200,
                message: 'Success',
                data: result
            })
        } catch (error) {
            logger.error(`error: ${error.message}`)
            return next(error.message)
        }
    })
    

    【讨论】:

    • 没关系。我不想把这个logger.error(error) 放在整个应用程序中。
    • 然后你必须创建一个中间件并将处理函数作为回调传递给你的处理函数,这将允许在你可以应用错误处理的 try/catch 的上下文中执行函数
    • 谢谢。但是有一个默认的错误处理函数,如unhandledRejectionuncaughtException。这里我想像这样在整个应用程序的一个try-catch块中捕获错误。
    • 这个没有从 try-catch 块中捕获错误。它只捕获unhandledRejection
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多