2014-04-01 17 views
0

我想阻止我的NodeJS應用程序崩潰,並閱讀使用域的方式來做到這一點。儘管如此,我仍然有點困惑,但遵循了我所看到的設置。這是否設置正確?我需要改變什麼嗎?謝謝。我正在爲nodejs正確設置域嗎?

var express = require('express'); 
var http = require('http'); 
var path = require('path'); 
var d = require('domain').create(); 

var app = express(); 

app.configure(function() { 

    //set up express 
    app.set('port', process.env.PORT || 3000); 

    app.use(app.router); 
    app.use(function(req,res){ 
     res.redirect('/error'); 
    }); 

}); 


//launch 
d.on('error', function(er) { 
    console.log('Error!', er.message); 
}); 

d.run(function() { 
    http.createServer(app).listen(app.get('port'), function(){ 
     console.log('Express server listening on port ' + app.get('port')); 
    }); 
}); 

當我在其中一個路徑文件中創建錯誤時,它似乎工作正常,但錯誤未記錄。我應該把它登錄到一個文件或一些東西,所以我可以稍後檢查錯誤?

回答

1

那麼,根據NodeJS文檔,你所做的是一個不好的做法,因爲每次發生錯誤時都可能發生內存泄漏。 domain api docs page有一個正確的方法來做到這一點。我不知道爲什麼console.log不起作用,但是 - 日誌文件可能是一個好主意。另外請注意,域的API仍然不穩定,可能會改變。

簡而言之,您應該優雅地處理您的錯誤,並在發生意外錯誤時啓動新的工作進程(使用羣集模塊來啓動和停止遇到問題的工作人員)。

從文檔,這是你在做什麼應該做的,看起來非常接近,你在做什麼:

// XXX WARNING! BAD IDEA! 

var d = require('domain').create(); 
d.on('error', function(er) { 
    // The error won't crash the process, but what it does is worse! 
    // Though we've prevented abrupt process restarting, we are leaking 
    // resources like crazy if this ever happens. 
    // This is no better than process.on('uncaughtException')! 
    console.log('error, but oh well', er.message); 
}); 
d.run(function() { 
    require('http').createServer(function(req, res) { 
    handleRequest(req, res); 
    }).listen(PORT); 
});