在node.js中捕获异常 [英] Catch exception in node.js
问题描述
我有一个简单的程序,需要确保可以连接到Redis服务器。我使用node-redis进行连接,需要等待Redis启动。我使用这段代码:
I have a simple program, which needs to make sure I can connect to a Redis server. I use node-redis to connect and need to wait until Redis is started. I use this piece of code:
function initializeRedis(callback) {
(function createClient(){
var runner;
try {
client = redis.createClient();
} catch (e) {
setTimeout(createClient, 1000);
}
callback();
})();
};
initializeRedis(function() {
// Work here
});
这是因为没有try / catch,我从node.js得到了一个异常:
This is because without the try/catch, I got an exception from node.js:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused
at Socket.<anonymous> (/var/www/php-jobs/node_modules/redis/index.js:88:28)
at Socket.emit (events.js:64:17)
at Array.<anonymous> (net.js:830:27)
at EventEmitter._tickCallback (node.js:126:26)
当我启动redis-server(Ubuntu计算机)并启动此脚本时,一切正常。如果我停止redis-server并启动脚本,它不会捕获该异常,但仍会引发该异常。那怎么可能?我有一条try / catch语句!
When I start redis-server (Ubuntu machine) and start this script, everything works fine. If I stop redis-server and start the script, it doesn't catch the exception and still throws this same exception. How is that possible? I have a try/catch statement!
推荐答案
在 client = redis.createClient();
,设置错误
事件的处理程序:
After client = redis.createClient();
, set a handler for the error
event:
client.on('error', function(err) {
// handle async errors here
});
看看堆栈跟踪-您的代码不在其中,所以没有地方尝试/捕获可能会捕获错误。
Have a look at the stack trace - your code isn't in it, so there's no place where a try/catch could catch the error.
这篇关于在node.js中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!