捕获自定义错误无法在Bluebird中运行

时间:2016-05-05 17:39:42

标签: node.js promise bluebird

我正在尝试抛出然后在Bluebird承诺链中捕获自定义错误,但我无法捕获自定义错误。例如:

function login(req, res, next) {
  function LoginError() {}

  return User.where('id', req.body.userId).fetch()
    .then(function (location) {
      if (req.body.password !== location.get('password')) {
        throw new LoginError();
      }

      // returns a promise
      return Subscription.where('userId', location.get('userId')).fetch();
    })
    .then(function (subscription) {
      return res.send(JSON.stringify(subscription));
    })
    .catch(LoginError, function (err) {
      return res.send('Login error');
    })
    .catch(function (err) {
      res.send('Other error: ' + JSON.stringify(err));
    });
}

当密码不匹配且抛出LoginError时,错误将在第二个catch块中捕获,而不是LoginError的catch块。我做错了什么?

我正在使用Express.js,Bluebird和Bookshelf / Knex,User是一个Bookshelf模型。

1 个答案:

答案 0 :(得分:4)

Bluebird通过继承来区分错误构造函数和catch中的谓词函数:

  

将参数视为您想要的错误类型   过滤器,您需要构造函数具有其.prototype属性   instanceof Error

     

这样的构造函数可以像这样最小化地创建:

function MyCustomError() {}
MyCustomError.prototype = Object.create(Error.prototype);

您需要为LoginError执行相同操作。

或者,如果您使用的是ES6,那么class LoginError extends Error {}

相关问题