I have a Node.js App and is using a function that returns a Promise, but it seems in some conditions it gives:
Unhandled rejection Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
And my server crashes.
Here is a simplifed code that does the crash if wifi is turned off:
checkip.getExternalIp().then(function (ip) {
console.log("External IP = "+ip);
});
Is there a way to handle something like this?
you have two options. You can slap a .catch
call on to the end of the promise, or you can provide a second callback to .then
which runs in the failed case:
checkip.getExternalIp().then(function (ip) {
console.log("External IP = "+ip);
}).catch(function(err) {
// handle error here
});
or
checkip.getExternalIp().then(function (ip) {
console.log("External IP = "+ip);
}, function(err) {
// handle error here
});
ES2015 promises follow the A+ spec . Thus, any promise has the possibility of generating an error that can be caught. So, to trap the error you are receiving simply supply a catch
handler:
checkip.getExternalIp()
.then(then_handler)
.catch(catch_handler);
More complete examples are in the documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.