捕获自定义错误在 Bluebird 中不起作用

Catching custom error not working in 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 模型。

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

For a parameter to be considered a type of error that you want to filter, you need the constructor to have its .prototype property be instanceof Error.

Such a constructor can be minimally created like so:

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

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

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