NPM请求库的错误条件

Error conditions for NPM Request lib

本文关键字:错误条件 请求 NPM      更新时间:2023-09-26

我的请求函数中的回调传递了一个错误。我试图确定在什么情况下错误会被传递给回调。

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if(error){
   //why or when would an error be created?
  }
  else if (response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
  else{
   // when would this happen ?
   }
})

文档似乎没有涵盖什么条件会导致创建和传递错误对象。现在我只是假设除了200或300之外的任何东西都会导致创建错误,但我只是猜测。

请求库内部使用node.js http模块进行GET请求。来自文档:

如果在请求过程中遇到任何错误(使用DNS解析、TCP级别错误或实际HTTP解析错误)"错误"在返回的请求对象上发出事件。

我想你必须查看http模块的源代码才能准确地找出错误。