0

Normally, everything works, but when there is no internet connection my app throws an error:

    events.js:160
      throw er; // Unhandled 'error' event
      ^

   Error: getaddrinfo ENOTFOUND

    /* my code - putting this to try...catch have no effect: */
    var http = require('http');
    // (...)
    var req = http.request(options, response => {
       /* ... */
    });
    req.write(data);
    req.end();

So what can I do when internet connection shuts down and I would like to prevent my app from stopping?

  • You need to show the rest of your server code and I'd also recommend giving more information about how the app is running, is it running via `node` or is it being run by a process manager like `pm2` or `forever`? Are you running it locally? Is being run at `localhost`? You don't need an internet connection or even an active network connection in order for the `http` module to create a server that is listening locally. – peteb Apr 06 '17 at 16:22
  • @peteb I am running it locally by node, but the domain which I am requesting to is on external server; i am not creating a server but only get data by code above and show response by console.log – Jimi Alvaro Apr 06 '17 at 16:40
  • If something is offline and not local, you can't request it. Thats just how it works. – peteb Apr 06 '17 at 16:42
  • @peteb but I want to prevent situation when my app is running on server, trying connect to external server but by unexplained reason there is no internet connection on my server-side (is this even possible?). When that case occurs my app will crash. – Jimi Alvaro Apr 06 '17 at 16:59

1 Answers1

1

To prevent your app from stopping when external server's internet connection is down, you can catch getaddrinfo ENOTFOUND error and return error message to your end client. Please check this SO on how to catch getaddrinfo ENOTFOUND error.

In your case, the code would be:

var http = require('http');
// (...)
var req = http.request(options, response => {
   /* ... */
});
req.on('error', function (err) {
    // Check error type and console.log corresponding message.
});
req.write(data);
req.end();
Community
  • 1
  • 1
shaochuancs
  • 15,342
  • 3
  • 54
  • 62