【问题标题】:How can I catch Exception using co module on Node.js?如何在 Node.js 上使用 co 模块捕获异常?
【发布时间】:2016-10-14 14:55:18
【问题描述】:

我在 Sai 框架上使用 co 模块进行编码。

我想捕捉 InvalidError 但错误日志显示“未定义”。

如何修复此代码?

Co 模块无法捕获 ErrorType 规范??

detail: function (req, res) {
  co(function *() {
    let errors = [];
    const text = req.param('text');

    if (text.length <= 0) {
      throw new InvalidError('text is required');
    }

  }).catch((InvalidError, err) => {
    sails.log.warn(err);
    errors.push(err.message);
    req.flash('errors', errors);
    res.redirect('/somewhere/view');
  }).catch((Error, err) => {
    sails.log.error(err);
    res.serverError(err);
  });
}

错误日志在这里

warn: undefined
error: undefined
error: Sending empty 500 ("Server Error") response

【问题讨论】:

    标签: javascript node.js sails.js bluebird co


    【解决方案1】:

    catch 方法只接受一个参数:err。试试:

    .catch(err => {
        sails.log.warn(err);
        errors.push(err.message);
        req.flash('errors', errors);
        res.redirect('/somewhere/view');
    })
    

    【讨论】:

      【解决方案2】:

      您没有使用 Bluebird,是吗? standard catch method 没有 error type filtering,你需要自己做:

      .catch(err => {
        if (err instanceof InvalidError) {
          sails.log.warn(err);
          errors.push(err.message);
          req.flash('errors', errors);
          res.redirect('/somewhere/view');
        } else if (err instanceof Error) {
          sails.log.error(err);
          res.serverError(err);
        } else {
          console.error("You've thrown a non-error! Shame on you!");
        }
      });
      

      【讨论】:

      • 感谢您的建议!我正在使用蓝鸟。如果使用 Bluebird,我可以选择其他选项吗??
      • 好吧,you 可能正在使用 Bluebird,但 co 没有 :-) 您可以使用 Bluebirds 实现覆盖全局 Promise 变量,或者您可以强制转换由co(…) 向蓝鸟返回的承诺,如herethere 所述
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 2010-09-07
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多