Ben*_*aum 8 node.js promise es6-promise
我知道如何处理promises中的特定错误但我有时会看到如下代码片段:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
Run Code Online (Sandbox Code Playgroud)
有时,我得到无效的JSON,这会在JSON.parse throws 时导致静默失败.一般来说,我必须记住.catch在我的代码中为每个承诺添加一个处理程序,当我不在时,我无法找到我忘记的地方.
如何在代码中找到这些被抑制的错误?
Ben*_*aum 17
从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
});
Run Code Online (Sandbox Code Playgroud)
这样就结束了未处理的拒绝问题以及在代码中跟踪它们的难度.
这些事件尚未反向移植到旧版本的NodeJS,并且不太可能.您可以使用扩展本机promise API的promise库,例如bluebird,它将触发与现代版本相同的事件.
还值得一提的是,有几个用户态承诺库提供未处理的拒绝检测设施以及更多,如bluebird(也有警告)和何时.