【问题标题】:How do you catch `Error: ENOENT: no such file or directory` with winston?你如何用winston捕捉`错误:ENOENT:没有这样的文件或目录`?
【发布时间】:2018-10-15 06:45:01
【问题描述】:

我正在使用带有 winston 记录器的 express。当 express 尝试提供路径不准确的文件时,我看到错误 Error: ENOENT: no such file or directory。这是预期的行为。但是,错误不会通过 winston 记录(因此不会被推送到我的 slack webhook)。它被记录到节点控制台,但没有被我的 winston 记录器拾取。我尝试将 .sendFile() 包装在 try/catch 中,但这也不起作用。

const logger = require('winston');

const serveFile = ({ filePath, fileType }, res) => {
  logger.verbose(`serving file: ${filePath}`);
  const sendFileOptions = {
    headers: {
      'X-Content-Type-Options': 'nosniff',
      'Content-Type'          : fileType,
    },
  };
  try {
    res.status(200).sendFile(filePath, sendFileOptions);
  } catch (error) {
    logger.error(error);
  }
};

module.exports = serveFile;

【问题讨论】:

    标签: javascript node.js express winston sendfile


    【解决方案1】:

    我需要使用 sendFile() 作为其第三个参数的回调函数,而不是 try/catch。

    const logger = require('winston');
    
    const serveFile = ({ filePath, fileType }, res) => {
      logger.verbose(`serving file: ${filePath}`);
      const sendFileOptions = {
        headers: {
          'X-Content-Type-Options': 'nosniff',
          'Content-Type'          : fileType,
        },
      };
      res.status(200).sendFile(filePath, sendFileOptions, (error) => {
        if (error) {
          logger.error(error);
        }
      });
    };
    
    module.exports = serveFile;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 2019-03-09
      • 2017-12-28
      • 2022-01-16
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多