处理Javascript承诺中的拒绝错误

我有一个Node.js应用程序,并使用一个函数返回一个Promise,但它似乎在某些条件下给出:

Unhandled rejection Error: getaddrinfo ENOTFOUND at errnoException (dns.js:37:11) at Object.onanswer [as oncomplete] (dns.js:124:16) 

而我的服务器崩溃。

这是一个简化的代码,如果wificlosures,会发生崩溃:

 checkip.getExternalIp().then(function (ip) { console.log("External IP = "+ip); }); 

有办法处理这样的事情吗?

你有两个select。 您可以将.catch调用放在承诺的最后,也可以提供第二个callback.then然后在失败的情况下运行。

 checkip.getExternalIp().then(function (ip) { console.log("External IP = "+ip); }).catch(function(err) { // handle error here }); 

要么

 checkip.getExternalIp().then(function (ip) { console.log("External IP = "+ip); }, function(err) { // handle error here }); 

ES2015承诺遵循A +规范 。 因此,任何承诺都有可能产生可被捕获的错误。 所以,为了捕获你收到的错误只需提供一个catch处理程序:

 checkip.getExternalIp() .then(then_handler) .catch(catch_handler); 

文档中有更完整的示例。