在以下路由中,我从URL接收user_id,并使用mongoose从mongoDb提取数据。 假设我的网址看起来像“ http://localhost/user/5eb47018d2ca374ea4cb36431”,我得到了期望的结果。但是,如果我更改ID值,例如“ 5eb47018d2ca374ea4cb36431234”,则会返回服务器错误。这就是我不想返回的内容。相反,我想返回“找不到用户”。如何处理catch块中的错误以发送所需的消息,例如“找不到用户”。
原谅英语错误。
router.get('/user/:user_id', async(req, res) => {
try {
const profile = await Profile.findOne({ user: req.params.user_id }).populate('user', ['name',
'avatar']);
if (!profile) return res.status(400).json({ msg: 'No user for this profile' });
res.json(profile);
}catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
配置文件表中的数据
_id
:
5eb719425b385c31e475fa0d
skills
:
Array
0
:
"HTML"
1
:
"CSS"
2
:
"JS"
3
:
"PHP"
4
:
"JQUERY"
user
:
5eb47018d2ca374ea4cb3643
company
:
"xxxx"
website
:
"https://xxxx.xyz"
location
:
"xxxx"
bio
:
"Developer of this proect"
status
:
"developer"
githubusername
:
"notspecified"
social
:
Object
facebook
:
"https://facebook.com/xxxx"
twitter
:
"https://twitter.com/xxx"
experience
:
Array
date
:
2020-05-09T20:57:38.178+00:00
__v
:
0
答案 0 :(得分:1)
用户类型是什么?如果收到的ID与个人资料ID相同,请尝试使用_id代替用户
答案 1 :(得分:1)
在try
块中的代码中,检查user_id
是否有效。如果ID无效,则会引发错误。因此,将此if (!mongoose.Types.ObjectId.isValid(req.params.userid)) return res.status(400).json({ msg: 'No user for this profile' });
放在try块中,如下所示:
router.get('/user/:user_id', async(req, res) => {
try {
if (!mongoose.Types.ObjectId.isValid(req.params.userid))
return res.status(400).json({ msg: 'No user for this profile' });
const profile = await Profile.findOne({ user: req.params.user_id }).populate('user', ['name',
'avatar']);
if (!profile) return res.status(400).json({ msg: 'No user for this profile' });
res.json(profile);
}catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
在参数之前检查参数是否为有效的ObjectId,如果不是有效的ID,则只需返回所需的响应即可。如果有效,则进一步进行检查以确认其可用性。