防止节点types错误崩溃的应用程序

使用简单的request.js http客户端我注意到,有时一个简单的TypeError可能会崩溃整个节点的应用程序。 举一个例子:

 request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Print the google web page. } }) 

现在,假设(谷歌的情况下)的情况下,谷歌没有回应,连接只是挂起,然后超时。 此代码简单地崩溃节点应用程序,因为response未定义,因此无法读取response.statusCode 。 这起泡到事件循环,并触发错误的崩溃:

 TypeError: Cannot read property 'statusCode' of undefined 

什么是最简单的方法,我可以防止这种情况发生? 在检查statusCode之前,我可以添加一个检查error值的例子:

 request('http://www.google.com', function (error, response, body) { if (!error) { if (response.statusCode == 200) { // do stuff } } }) 

但是,如果可能的话,我宁愿不添加不必要的行。 我可能会在这里错过一些明显的东西 任何指针不胜感激。 谢谢。

简短的回答:这就是你得到的。 详细答案:

  • 总是检查错误
  • 始终检查您的数据

所以,这样的事情是非常好的:

 if (!error && body) { //do whatever you want with your body } if (!error && response) { //do whatever you want with response } 

在尝试访问对象之前,必须确保对象存在(在不能保证对象存在的情况下)。 另外,看看maybe2模块。 有了这个模块,你可以这样写:

 if (!error && maybe(response).getOrElse({}).statusCode == 200) { //your code here } 
  • 使用node.js集群模式,在您的应用程序前面使用像永远和/或负载平衡代理(如nginx)的pipe理程序模块。 这样,如果一个请求失败,其他请求将由您的应用程序的其他实例履行。
  • 准备在客户端处理错误,并在失败时重复请求。