如何处理http.get响应中未被捕获的exception

我有这个代码使用API​​从第三方网站下载新闻提要。 它的设置每5秒运行一次,并且可能会发生任何新闻交易。 这个问题似乎是在没有发生新的事务时。

通过添加process.on('未捕获的exception',函数(error){console.log(“hmph”)})cron作业能够在5秒后继续,所以我被诱惑离开它。 然而,我添加了console.log(“hmph”)到现在我很困惑。

第一次,控制台会写hmph。 5秒钟后它会写hmph hmph

等等。 我知道我一定错过了一些东西,但我不太清楚它是什么。 我已经尝试在else语句中执行request.end(),但错误仍然激发。

没有process.on('uncaught …')抛出的错误是:

events.js:71个参数[1]; //未处理的错误事件^错误:在TCP.onread(net.js:403:27)的Socket.socketOnData(http.js:1367:20)

用proccess.on('uncaught …')console.log(错误)是:

{[Error:Parse Error] bytesParsed:161,code:'HPE_INVALID_CONSTANT'}

我如何正确处理这个错误?

缩写代码:

var job = new cronJob('*/5 * * * * *', function(){ var request = http.get({ host: 'www.example.com', path: '/news_feed?apicode=myapicode', port: 80, headers: { 'accept-encoding': 'gzip' } }) request.on('response', function(response){ if (response.statusCode == 200){ // gunzip response, save response to mongodb } else { // here is where the error is occuring process.on('uncaughtException',function(error){ console.log(error); console.log("hmph"); } }); }, null, true); 

每次发出请求时,都会绑定一个新的uncaughtExceptionexception处理程序,因此发送第一个请求时,会绑定第一个请求,当它发生故障时会打印一个错误,然后在下一个请求中添加另一个处理程序,当第一个和第二个处理程序都不能运行的时候。

检查错误,并在这里谈论这种types的错误: https : //github.com/joyent/node/issues/3354看起来你连接到的服务器可能做一些奇怪的事情。 最简单的解决scheme可能是现在使用uncaughtException处理程序。 这就是说,这不是理想的,你不应该把它作为这样的未来问题的一般解决scheme。

 var job = new cronJob('*/5 * * * * *', function(){ var request = http.get({ host: 'www.example.com', path: '/news_feed?apicode=myapicode', port: 80, headers: { 'accept-encoding': 'gzip' } }); request.on('response', function(response){ if (response.statusCode == 200){ // gunzip response, save response to mongodb } }); }, null, true); process.on('uncaughtException',function(error){ console.log(error); console.log("hmph"); });