我试图抛出然后在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在 catch 通过继承:
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中不起作用
发布评论