首页 > 解决方案 > 如何抛出自定义错误?

问题描述

我正在尝试使用passport-jwt策略进行身份验证。

这是我的代码:-

router.post('/register', async (req, res) => {
    const { username, email } = req.body;
    try {
        const user = await User.findOne({ username });
        if (user) {
            throw new Error('User with same username already exists !!');
        }
        const newUser = new User({
            username,
            email
        })
        const salt = await bcrypt.genSalt(10);
        newUser.password = await bcrypt.hash(req.body.password, salt);
        const savedUser = await newUser.save();
        res.json({
            status: 200,
            'Content-Type': 'Application/Json',
            'message': `You have successfully regirstered yourself, ${savedUser.username}!`
        })
    } catch (err) {
        err.statusCode = 500;
        console.log(err.message);
        res.header({
            status: '200',
            'Content-Type': 'Application/Json',
        });
        res.json(err);
    }
});

现在这条路线工作得很好,到目前为止它正在做所有的事情。唯一的问题是,当我找到现有用户时,我想用自定义消息抛出一个新错误。Javascript 有这个Error类,我可以用它来抛出这些错误。

当它捕获错误时会出现问题。当 I 时console.log(err.message),我可以完美地看到我的自定义消息。但是err我通过响应返回的对象res.json(err)没有任何message但只有statusCode.

我想知道为什么会发生这种情况以及解决方案是什么?现在,我正在做这样的事情:-

res.json({
    statusCode: 500,
    message : err.message
});

但我想返回填充了和字段的err对象。statusCodemessage

标签: javascriptnode.jstry-catch

解决方案


You can create your own Error class which can take more than one parameter in the constructor. This class has to extend base Error JavaScript class. For example:

class MyCustomError extends Error {
  constructor(msg, statusCode) {
    super(msg);
    this.statusCode = statusCode;
    this.name = MyCustomError.name;
  }
}

function throwCustomError() {
  throw new MyCustomError('Some custom message', 404);
}

try {
  throwCustomError();
} catch (error) {
  console.log(error.message);
  console.log(error.statusCode);
  console.dir(error);
}

Remember that you have to call super on the beginning of the constructor if you are extending another class


推荐阅读