【发布时间】:2020-05-15 07:14:04
【问题描述】:
在下面的路线中,我从 url 接收 user_id 并使用 mongoose 从 mongoDb 获取数据。 假设我的 url 看起来像 'http://localhost/user/5eb47018d2ca374ea4cb36431' 我得到了想要的结果。但是,如果我更改像 '5eb47018d2ca374ea4cb36431234' 这样的 id 值,它会返回服务器错误。这是我不想回来的。相反,我喜欢返回“未找到用户”。如何处理 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
【问题讨论】: