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

问题描述 投票:0回答:2

我想捕获所有错误强大的可能会抛出文件上传。到目前为止,我在最基本的一个上失败了:文件夹不存在。请注意,仅为测试目的生成此错误,方法是为要保存的文件添加不存在的路径。代码本身工作正常,没有生成的错误。

以下是我尝试过度杀戮/垃圾邮件尝试/捕获的示例:

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...
node.js error-handling formidable
2个回答
0
投票

试试这个:

process.on('uncaughtException', function(err) {
    // you can get all uncaught exception here. 
    console.log(err)
})

0
投票
// 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));
});
© www.soinside.com 2019 - 2024. All rights reserved.