异步的未处理异常等待

时间:2017-12-10 18:56:11

标签: javascript node.js

我正在尝试将旧的回调样式函数转换为异步等待。但是我无法理解如何捕获未处理的异常。

例如,假设我有一个功能

  apiCall(input, function(error, result) {
    if (error) {
      console.log(error);
    } else {
      console.log(result);
    }
  });

我转换为Promise

function test1(input) {
  return new Promise(function(resolve, reject) {
    apiCall(input, function(err, result) {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}

然后我称之为

test1(4)
  .then(function(result) {
    console.log('Result: ' + result);
  })
  .catch(function(errorr) {
    console.log('My Error: ' + errorr);
  });

即使我尝试返回错误,有时此功能也会崩溃。让我们说磁盘错误,JSON解析错误等。我没有处理的一些错误。我只能用

来捕捉这些错误
process.on('uncaughtException', function(error) {
  console.log('uncaughtException' + error);
});

我有办法用异步等待来捕获各种错误吗?

编辑:这是完整的github回购,供您试用

https://github.com/tosbaha/promise

运行节点testme.js并看到它崩溃并且异常处理程序不运行。

可能崩溃的文件是this任何功能都可能崩溃,但我无法预见到各种错误。这就是为什么我正在寻找一个解决方案来捕获此文件中的错误。

如果您使用node testme.js在我的仓库中运行代码,您将收到以下错误

        results[trackingId] = trackingArray.doesntExist.Something;
                                                        ^
TypeError: Cannot read property 'Something' of undefined

如您所见,catch处理程序未捕获错误。

1 个答案:

答案 0 :(得分:0)

如果apiCall在没有调用回调的情况下崩溃(有错误),我认为它会抛出一些错误,可以使用try... catch块在其外部处理(虽然我不确定,因为我不知道apiCall)的内部代码。

您可以尝试以下操作:

function test1(input) {
  return new Promise(function(resolve, reject) {
      try {
        apiCall(input, function(err, result) {
          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
        });
      } catch (e) {
        // reject the errors not passed to the callback
        reject(e);
      }
  });
}
相关问题