2017-08-05 128 views
-1
var http = require('http'); 
var url = require('url'); 
var server = http.createServer(function(request, response) { 
    http.get('http://nodejs.org/dist/index.json', (res) => { 
     response.write("Inside http"); 
     response.end(); 
    }).on('error', function(e) { 
     console.log(e); 
    }); 
}); 
server.listen(3000); 

在上面的代碼運行,既不控制走了進去http.get也不拋出任何error.What我失去了在這裏捕捉錯誤?錯誤處理http.get請求節點JS

注意:服務器創建在3000

+0

尋求幫助時,請打破你的代碼到合理的線條和格式,併合理地縮進你的代碼(當*不*求助時,這是一個好主意)。 (Alon Eitan和我已經在這個場合爲你修好了) –

+0

我試着格式化你的代碼,但是我不會添加換行符,請[編輯]你的文章並正確設置代碼的格式,使其更具可讀性 –

+0

哦,TJ只是爲你做了:) –

回答

0

在您的應用程序中添加應用程序級錯誤處理程序。如果出現問題,將捕獲的錯誤

process.on('uncaughtException', function (err) { 
    // This should not happen 
    logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err); 
}); 
0

看來http.get應放置在下面的方式爲它正常工作:

var http = require('http'); 
console.log('Before server'); 
var server = http.createServer(function(request, response) { 
    console.log('Request received'); 
}); 
server.listen(3000, function() { 
    http.get('http://nodejs.org/dist/index.json', (res) => { 
    console.log('Inside http'); 
    }) 
    .on('error', (e) => { 
    console.error(`Got error: ${e.message}`); 
    }); 
});