我知道如何处理 Promise 中的特定错误,但有时我的代码如下所示:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
有时,我会得到无效的 JSON,这会在JSON.parse
throw
s. 一般来说,我必须记住为.catch
我的代码中的每一个承诺添加一个处理程序,当我不这样做时,我无法找出我忘记的地方。
如何在我的代码中找到这些被抑制的错误?
我知道如何处理 Promise 中的特定错误,但有时我的代码如下所示:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
有时,我会得到无效的 JSON,这会在JSON.parse
throw
s. 一般来说,我必须记住为.catch
我的代码中的每一个承诺添加一个处理程序,当我不这样做时,我无法找出我忘记的地方。
如何在我的代码中找到这些被抑制的错误?
我们终于在 Node.js 15 中解决了这个问题,它花了 5 年时间,但原生的 promise 拒绝现在表现得像未捕获的异常——所以只需添加一个process.on('uncaughtException'
处理程序就可以了。
从 io.js 1.4 和 Node 4.0.0 开始,您可以使用该process
"unhandledRejection"
事件:
process.on("unhandledRejection", function(reason, p){
console.log("Unhandled", reason, p); // log all your errors, "unsuppressing" them.
throw reason; // optional, in case you want to treat these as errors
});
这结束了未处理的拒绝问题以及在代码中追踪它们的困难。
这些事件还没有向后移植到旧版本的 NodeJS,而且不太可能。您可以使用扩展原生 Promise API 的 Promise 库,例如bluebird,它将触发与现代版本相同的事件。
还值得一提的是,有几个 userland promise 库提供了未处理的拒绝检测功能,还有更多,例如bluebird(也有警告)和when。