javascript - 如何抛出自定义错误?
问题描述
我正在尝试使用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
对象。statusCode
message
解决方案
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
推荐阅读
- ios - 具有演示样式 formSheet 的模态 UIViewController 在 iPhone XS Max 和 iPhone XR 上无法正确显示
- appium-ios - 错误:连接 ECONNREFUSED 127.0.0.1:8100
- google-cloud-storage - 如何将 Power BI 服务连接到谷歌云存储(Bucket)
- reactjs - 在初始化 BrowserRouter 的组件中获取 location 属性
- c# - 当按钮获得焦点时,WPF阻止执行命令
- linux - 重定向到 dev/null
- c# - 将类型传递给表达式函数输出
- linux - 哪个线程监听特定的 UDP 端口
- python - 扩展 pandas 数据框以包含“缺失”周
- c++ - 使用动态分配将 char* 复制到另一个 char**