【问题标题】:When using Multiparty in Node, how do I properly throw an error?在 Node 中使用 Multiparty 时,如何正确抛出错误?
【发布时间】:2017-11-21 00:57:12
【问题描述】:

我正在尝试调用错误处理函数并返回响应而不使进程崩溃。代码很简单:

// Parts are emitted when parsing the form
form.on('part', function(part) {
  // You *must* act on the part by reading it
  // NOTE: if you want to ignore it, just call "part.resume()"

  if (!part.filename) {
    // filename is not defined when this is a field and not a file
    console.log('got field named ' + part.name);
    // ignore field's content
    part.resume();
  }

  if (part.filename) {
    // filename is defined when this is a file
    console.log('got file named ' + part.filename);
    if (part.filename == "CHFILE.TXT"){
      records = CHfilter(part);
    } else if (part.filename == "FCFILE.TXT"){
      records = FCfilter(part);
    } else if (part.filename == "TRFILE.TXT"){
      records = TRfilter(part);
    } else if (part.filename == "TLFILE.TXT"){
      records = TLfilter(part);
    } else {
      throw new Error("File "+part.filename+" is not a recognized file.")
    }

    // ignore file's content here
    part.resume();
  }

  part.on('error', function(err) {
    // decide what to do
    if (err) Log.resError(err, req, res);
    console.log("error function");
    res.send(err);
  });
});

但是当我使用任何其他名称上传文件时,它会引发错误,但 part.on('error',... 函数永远不会运行。所以客户端永远不会得到响应。我错过了什么?

谢谢!

【问题讨论】:

  • 您是否也尝试在form 上收听error 事件? form.on('error', ...)
  • 我没有,但如果这有效,那不是一个错误吗?我从“部分”抛出错误,所以部分错误处理程序应该触发。没有?
  • 不一定,不,这取决于multiparty 在内部如何处理错误。甚至可能在事件处理程序中抛出错误不会导致任何error 事件被发出。

标签: javascript node.js express file-upload multipart


【解决方案1】:
form.emit('error', new Error("File "+part.filename+" is not a recognized file."));

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2020-08-29
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多