简体   繁体   中英

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

I am using express with winston logger. I am seeing an error Error: ENOENT: no such file or directory when express tries to serve a file for which the path is not accurate. This is the expected behavior. However, the error does not get logged through winston (and thus doesn't get pushed to my slack webhook). It gets logged to the node console, but it is not picked up by my winston logger. I tried wrapping the .sendFile() in a try/catch but that did not work either.

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;

Rather than a try/catch, I needed to use the callback function that sendFile() takes as its third argument.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM