【问题标题】:Logging errors in NodeJS / Express / React stack在 NodeJS / Express / React 堆栈中记录错误
【发布时间】:2018-12-21 08:29:15
【问题描述】:

我一直在使用 React、NodeJS/Express 开发一个应用程序。我的问题是,当错误在后端 API 服务器上时,我如何记录错误(在节点控制台或外部文件中)?

例如,假设我有一个 api 端点“/api/example”,它将从数据库中获取数据并处理数据。在那个过程中,我有一个类似的数据库类

class DB {
    update(sql) {
           ...
    }
    ...
}

但是当我调用该方法时,我打错了,所以我调用了db.updates(sql),控制台不会显示像Uncaught error: db.updates is not a function 这样的任何错误,并且请求将一直挂起,直到它终止。

所以我的问题是如何让错误出现在控制台上?这很烦人,因为这比它应该消耗的时间多得多。

我试过 morgan,它似乎只记录了 http 请求?我也尝试了 winston,但在日志文件或控制台中仍然看不到任何内容(尽管我不确定如何使用它。我已将我的 winston 记录器代码附在最底部)。

我以前没有遇到过这个问题,因为我以前一直使用像 ejs 这样的模板视图引擎,当发生这样的错误时,ejs 页面将呈现错误。现在有了 react 环境和一个只发送 json 响应的 API 服务器,页面就会进入组件的加载状态,直到 fetch 请求失败。

任何指针将不胜感激。 谢谢。

温斯顿 logger.js

import winston from 'winston'

const options = {
    file: {
        level: 'error',
        filename: `./logs/error.log`,
        handleExceptions: true,
        json: true,
        colorize: false,
    },
    console: {
        level: 'error',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

let logger = winston.createLogger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console)
    ],
    exitOnError: true,
});

logger.stream = {
    write: function (message, encoding) {
    transports (file and console)
        logger.info(message);
    },
};

export default logger

App.js

import logger from './logger'
import morgan from 'morgan'

...
app.use( morgan('combined', {stream: logger.stream}) )
...

【问题讨论】:

    标签: node.js reactjs express winston morgan


    【解决方案1】:

    您可以尝试将函数调用包装在 try/catch 块中并记录捕获的错误

    【讨论】:

    • 啊,我明白了,我想我会把所有的路线都包装在 try catch 块中。谢谢。
    【解决方案2】:

    在我的项目中,我们在路线中遇到错误(try/catch):

    router.get('/', function(req, res, next) {
      try {
        //get the data
        res.status(200).json(data);
      } catch (error) {
        next(error);
      }
    });
    

    并在 app.js 中管理答案:

    app.use(function (err, req, res, next) {
      //TODO implement error log (e.g. WINSTON)
      res.status(errorStatus).json({"status": err.status, "data": err.data, "message": err.message});
    });
    

    【讨论】:

    • 啊,我明白了,我想我会把所有的路线都包装在 try catch 块中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多