捕获自定义错误在Bluebird中不起作用 [英] Catching custom error not working in Bluebird

查看:76
本文介绍了捕获自定义错误在Bluebird中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图抛出然后在Bluebird Promise链中捕获自定义错误,但是我无法捕获到自定义错误.例如:

I am trying to throw and then catch a custom error in a Bluebird promise chain, but I can't get it to catch the custom error. For example:

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块中.我在做什么错了?

When the password doesn't match and it throws LoginError, the error is caught in the second catch block, not the catch block for LoginError. What am I doing wrong?

我正在使用Express.js,Bluebird和Bookshelf/Knex,其中User是Bookshelf模型.

I'm using Express.js, Bluebird, and Bookshelf/Knex where User is a Bookshelf model.

推荐答案

Bluebird在

Bluebird distinguishes error constructors from predicate functions in a catch by their inheritance:

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

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做同样的事情.

You will need to do the same for your LoginError.

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

Or if you're using ES6, then class LoginError extends Error {}.

这篇关于捕获自定义错误在Bluebird中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆