如何从节点中的 formidable.js 捕获任何错误?

How can I catch ANY error from formidable.js in node?

我想捕获文件上传时可能抛出的所有错误。到目前为止,我在最基本的问题上失败了:文件夹不存在。请注意,仅通过为要保存的文件添加不存在的路径来生成此错误以用于测试目的。代码本身运行良好,没有生成错误。

这是我试过的 overkill/spamming try/catch 的示例:

router.post('*', (req, res) => {
  try {
  // path is formed based on the type of file to be uploaded.
  // the file type is sent to different path. Ex.: logo: upload/logo
  const folder = path.join(__dirname, '../../public-NOT-EXISTING/media' + req.url);
  // check if folder exist, if not, create it
  // if (!fs.existsSync(folder)) {
  //   fs.mkdirSync(folder);
  //   console.log(util.yellow, 'Folder was created', util.Reset);
  // }
  // console.log(util.green,'Uploading to folder:', folder, util.Reset);

  const form = new formidable.IncomingForm();
  form.keepExtensions = true;
  form.uploadDir = folder;
  form.maxFieldsSize = 20 * 1024 * 1024;

  //Emitted whenever a new file is detected in the upload stream. Use this event if you want to stream the file to somewhere else while buffering the upload on the file system.
  /* this is where the renaming happens */
  form.on('fileBegin', function (name, file) {
    //rename the incoming file to the file's name
    file.path = form.uploadDir + file.name;
  });

  //Emitted whenever a field / file pair has been received. file is an instance of File.
  form.on('file', function(name, file) {
    console.log(util.magenta, 'Uploaded file name:', name, '(current name:', file.name,"')", util.Reset);
    res.status(200).send({message: 'File Uploaded'})
  });

  //Emitted when there is an error processing the incoming form. A request that experiences an error is automatically paused, you will have to manually call request.resume() if you want the request to continue firing 'data' events.
  form.on('error', function(err) {
    console.error('Something went wrong in uploading file:', err);
    res.status(500).send({message: err})
  });

  function errorHandle(err){
    console.error('Got the error in function cb', err);

  }
   form.parse(req, (errorHandle, fields, files) => {
      if (errorHandle)
        console.error('Got the error as CB argument', errorHandle);

      try{
      console.log('\n parsing uploaded file -----------');
      console.log('Fields', fields);
      console.log('Received:', Object.keys(files));
      console.log();
      }catch (e) {
        console.error('Got the error in "parse" function', e)
      }
    });
  }catch (e) {
    console.error('Got the error in general try/cath', e)
  }
});

但是,没有发现错误,服务器崩溃了:

Error: ENOENT: no such file or directory, open 'D:.... my path...'
Emitted 'error' event at:
    at fs.open (internal/fs/streams.js:279:12)
    at FSReqCallback.args [as oncomplete] (fs.js:145:20)
[nodemon] app crashed - waiting for file changes before starting...

试试这个:

process.on('uncaughtException', function(err) {
    // you can get all uncaught exception here. 
    console.log(err)
})
// Error Handlers
process.on('unhandledRejection', async err => {
  console.error('Unhandled rejection', JSON.stringify(err));
});

process.on('uncaughtException', async err => {
  console.error('Uncaught exception', JSON.stringify(err));
});