node.js - 在 NodeJS/Express/React 堆栈中记录错误

标签 node.js reactjs express winston morgan

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

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

这样的数据库类
class DB {
    update(sql) {
           ...
    }
    ...
}

但是当我调用该方法时,我犯了一个拼写错误,因此我调用了 db.updates(sql),控制台不会显示任何错误,例如 Uncaught error: db.updates is not a function 并且请求将挂起直到终止。

所以我的问题是如何让错误出现在控制台上?这变得很烦人,因为这占用了比应有的更多的时间。

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

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

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

winston 记录器.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}) )
...

最佳答案

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

关于node.js - 在 NodeJS/Express/React 堆栈中记录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316970/

相关文章:

node.js - phantom.js 中 phantom.exit 和 .close 有什么区别?

javascript - ReactJS CSS - 如何重新触发 @keyframes CSS 动画

node.js - 使用express和archiver创建zip

javascript - 如何从 Node 请求创建 RxJs Observable

node.js - Mongoose populate() 返回空数组

reactjs - 类型作为组件 Prop 的 child

javascript - React Native 发布构建崩溃问题,但在调试时它工作正常

node.js - 不断收到错误 : Configuration property "vidly_jwtPrivateKey" is not defined

javascript - Sails.JS HTTP + HTTPS

javascript - 将 gulp.start 函数迁移到 Gulp v4