How to catch getaddrinfo ENOTFOUND

吃可爱长大的小学妹 提交于 2019-12-01 03:27:19

You just need to handle the error event, as stated in the error message. According to the documentation:

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an 'error' event is emitted on the returned request object.

Here is a usage example:

var getRequest = _http.get(options, function(res) {
    // …
});
getRequest.on('error', function (err) {
    console.log(err);
});

which yields:

$ node test.js
{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

At the very top level, you can do

process.on('uncaughtException', function(err) {
  console.log('### BIG ONE (%s)', err);
});

if you using request npm

request
  .get('http://example.com/doodle.png')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']) // 'image/png'
  })
  .on('error', function(err) {   // <------- add this 
    console.log(err)
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!