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

编程入门 行业动态 更新时间:2024-10-09 23:14:07
本文介绍了捕获自定义错误在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在 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中不起作用

本文发布于:2023-11-02 06:05:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551575.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   中不   错误   Bluebird

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!