未从节点中的异步方法获得错误

Not getting error from async method in node

本文关键字:错误 异步方法 节点      更新时间:2023-09-26

我使用以下代码

require('./ut/valid').validateFile()
});

在验证文件中,当我在配置中发现一些重复时,我发送错误比如下面的

module.exports = {
    validateFile: function (req) {
...
if(dup){
console.log("Duplicate found: ");
return new Error("Duplicate found: ");
}

dup是true,错误应该被抛出,我应该如何"catch"在异步方法中?

我也试着跟随

require('./ut/valid').validateFile(function() {
    process.exit(1);
});

我在这里错过的是,我可以看到控制台日志…

你的方法不起作用,因为你正在做一些异步的事情。常见的解决方案是使用callbacks。在node.js中,通常使用一个称为错误优先回调的模式。

这意味着你需要传递一个callback函数给你的文件验证方法,然后返回一个错误或者你的文件:

  // './utils/validate.js'
  module.exports = {
    /**
     * Validates a file.
     *
     * @param {Function} next - callback function that either exposes an error or the file in question
     */
    file: function (next) {
      // ...
      if (duplicate) {
        console.log('Duplicate found!');
        var error = new Error('Duplicate File');
        // Perhaps enrich the error Object.
        return next(error);
      }
      // Eveything is ok, return the file.
      next(null, file);
    }
};

你可以这样使用:

 // './app.js'
var validate = require('./utils/validate');
validate.file(function (err, file) {
  if (err) {
    // Handle error.
    process.exit(1);
  }
  // Everything is ok, use the file.
  console.log('file: ', file);
});

我没有太多的知识在节点,但我可以告诉你,你正在返回一个错误对象,这不是一个错误从JS的角度来看,它只是一个对象,得到一个错误,你必须抛出一个错误,如:

throw true;

throw new Error("Duplicate found: ");

这样就会被当作错误处理,而不是作为返回值