如何在 node.js 中使用本地承诺全局处理异常?
How do I handle exceptions globally with native promises in node.js?
我知道如何 handle specific errors in promises 但有时我的代码片段如下所示:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
有时,我会得到无效的 JSON,这会在 JSON.parse
throw
时导致静默失败。一般来说,我必须记住为我的代码中的每个承诺添加一个 .catch
处理程序,如果我不这样做,我就无法找出我在哪里忘记了一个。
如何在我的代码中找到这些隐藏的错误?
编辑
我们终于在 Node.js 15 中解决了这个问题,这花了 5 年时间,但本机承诺拒绝现在表现得像未捕获的异常 - 所以只需添加一个 process.on('uncaughtException'
处理程序就可以了。
现代Node.js
从 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 中
这些事件尚未向后移植到旧版本的 NodeJS,而且不太可能。您可以使用扩展原生 promise API 的 promise 库,例如 bluebird,它将触发与现代版本中相同的事件。
还值得一提的是,有几个用户态承诺库提供未处理的拒绝检测功能以及更多,例如 bluebird (which also has warnings) and when。
我知道如何 handle specific errors in promises 但有时我的代码片段如下所示:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
有时,我会得到无效的 JSON,这会在 JSON.parse
throw
时导致静默失败。一般来说,我必须记住为我的代码中的每个承诺添加一个 .catch
处理程序,如果我不这样做,我就无法找出我在哪里忘记了一个。
如何在我的代码中找到这些隐藏的错误?
编辑
我们终于在 Node.js 15 中解决了这个问题,这花了 5 年时间,但本机承诺拒绝现在表现得像未捕获的异常 - 所以只需添加一个 process.on('uncaughtException'
处理程序就可以了。
现代Node.js
从 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 中
这些事件尚未向后移植到旧版本的 NodeJS,而且不太可能。您可以使用扩展原生 promise API 的 promise 库,例如 bluebird,它将触发与现代版本中相同的事件。
还值得一提的是,有几个用户态承诺库提供未处理的拒绝检测功能以及更多,例如 bluebird (which also has warnings) and when。