【问题标题】:How to throw exception for sync callback in nodejs?如何在nodejs中为同步回调抛出异常?
【发布时间】:2017-09-13 23:43:19
【问题描述】:

我想为 redis.set 回调抛出错误异常并在 try-catch 块中捕获,然后控制错误处理快速中间件。

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 状态。

【问题讨论】:

  • 这段代码怎么称呼?您如何发送响应?

标签: javascript node.js express try-catch


【解决方案1】:

您无法捕获异步事件。为此使用承诺:

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();
});

【讨论】:

  • 谢谢,不知道,这个回调是异步的。
猜你喜欢
  • 2012-02-03
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多