How do you catch `Error: ENOENT: no such file or directory` with winston?

How do you catch `Error: ENOENT: no such file or directory` with winston?

我正在使用 express 和 winston logger。当 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;

我需要使用 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;