首页 > 解决方案 > 在 NodeJS / Express / React 堆栈中记录错误

问题描述

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

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

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

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

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

我尝试了摩根,它似乎只是记录了 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

应用程序.js

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

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

标签: node.jsreactjsexpresswinstonmorgan

解决方案


在我的项目中,我们在路线中遇到错误(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});
});

推荐阅读