2017-09-13 70 views
-1

我想为redis.set回调抛出一个错误异常,并捕获try-catch块,然后控制错误处理express expressware。如何为nodejs中的同步回调抛出异常?

try { 
    redis.get('key', (err, reply) => { 
    if(err) throw err; 
    if(!reply) throw new Error('Can't find key'); 
    }); 
} 
catch{ 
    next(error); 
} 

的问题是,的try-catch根本就没有工作,错误会到节点控制台,而是服务器与200个状态响应。

+0

你怎么称呼这个代码?你如何发送回应? – alexmac

回答

0

你不能捕捉异步事件。使用的承诺为:

const getKey = new Promise((res,rej) => { 
    redis.get('key', (err, reply) => { 
    if(err) return rej(err); 
    res(reply); 
    }); 
}); 

所以可以这样做:

getKey.catch(next); 

getKey.then(reply => { 
    //do whatever 
    next(); 
}); 
+0

谢谢,不知道,这个回调是异步的。 – Quimmo