2011-12-28 106 views
3

我們正在尋找將node.js用於高度動態的項目。傳統上,我們使用Java,當遇到未處理的異常時,會拋出錯誤,但Web應用程序(通常)繼續服務於其他請求。處理node.js異常

但是,使用節點時,同一場景會導致進程終止。如果我們將此係統部署到生產環境中,並且整個服務器因未處理的異常而崩潰,我不願意想到會發生什麼情況。

我想知道是否有教程/工具/等,以幫助處理異常處理問題。例如,是否有一種方法來添加全局最後一種手段類型的異常?

回答

3
process.on('uncaughtException', function (err){ 
    console.error(err) 
}) 
3

如前所述here你會發現error.stack提供更完整的錯誤信息,如導致該錯誤的行號:

process.on('uncaughtException', function (error) { 
    console.log(error.stack); 
}); 
1

你應該使用Node.js domains

The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, you might have many connections open, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.

The better approach is send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.

鏈接的頁面有示例代碼,我稍微簡化了一下。它的工作方式如上所述。您可以調用您的服務器,使其在退出時自動重新啓動,或者use the worker pattern from the full example

var server = require('http').createServer(function(req, res) { 
    var d = domain.create(); 
    d.on('error', function(er) { 
    console.error('error', er.stack); 

    try { 
     // make sure we close down within 30 seconds 
     var killtimer = setTimeout(function() { 
     process.exit(1); 
     }, 30000); 
     // But don't keep the process open just for that! 
     killtimer.unref(); 

     // stop taking new requests. 
     server.close(); 

     // try to send an error to the request that triggered the problem 
     res.statusCode = 500; 
     res.setHeader('content-type', 'text/plain'); 
     res.end('Oops, there was a problem!\n'); 
    } catch (er2) { 
     // oh well, not much we can do at this point. 
     console.error('Error sending 500!', er2.stack); 
    } 
    }); 

    // Because req and res were created before this domain existed, 
    // we need to explicitly add them. 
    d.add(req); 
    d.add(res); 

    // Now run the handler function in the domain. 
    d.run(function() { 
    // your application logic goes here 
    handleRequest(req, res); 
    }); 
});