自定义错误(与Bluebird一起使用)从ES5迁移到ES6

时间:2017-08-22 17:23:05

标签: javascript error-handling ecmascript-6 bluebird

我正在尝试将此ES5语法转换为ES6 / ES7。这是我的ES5语法:

function UserNotFound(message) {
  this.name = 'UserNotFound';
  this.message = message || 'Default Message';
  this.stack = (new Error()).stack;
}

UserNotFound.prototype = Object.create(Error.prototype);
UserNotFound.prototype.constructor = UserNotFound;

以下是我如何捕捉错误:

.catch(UserNotFound, ()=> {
  console.log("User not found error caught");
})

目前有效。但是,在转换UserNotFound错误语法时,它不再捕获错误。在我认为我已将其正确转换为ES6 / ES7之后,它就是这样的样子:

export default {
  type: User,
  args: {
    email: {
      type: new GraphQLNonNull(GraphQLString)
    }
  },
  resolve(_, args) {
    const { email } = args;

    return Db.User.find({ where: { email }})
      .then(result => {
        if (!result) {        
          throw new UserNotFound();
        }

        const user = result.dataValues;
        return sendResetEmail(user).then(()=> user);
      })
      .catch(UserNotFound, ()=> {
        const username = getEmailUsername(email);

        return Db.User.create({
          email,
          username
        })
        .then(({dataValues}) => {
          const user = dataValues;
          return sendResetEmail(user).then(()=> user);
        });
      });
  }
}

0 个答案:

没有答案