【发布时间】:2021-11-30 16:14:49
【问题描述】:
我正在从 API 获取数据并将其显示在我的本地服务器上。
以下是我从 API 数据中获取与 ID 匹配的数据的代码:
router.get('/:id', async (req, res) => {
checkString(req.params.id)
try {
const person = await peopleData.getPersonById(req.params.id);
res.json(person);
} catch (e) {
res.status(404).json({ message: 'There is no person with that ID' });
}
如果没有匹配,我想像在 catch 块中一样显示消息,但代码不会去那里,因为从技术上讲,没有匹配不是错误。
所以我尝试了以下代码来获取此消息:
router.get('/:id', async (req, res) => {
checkString(req.params.id)
try {
const person = await peopleData.getPersonById(req.params.id);
if(!person) res.json('There is no person with that ID'); // Added new line here
res.json(person);
} catch (e) {
res.status(404).json({ message: 'There is no person with that ID' });
}
这可以工作,但它会将带有引号的消息打印为字符串,如果没有找到匹配项,有没有办法可以在 catch 块中显示消息?
【问题讨论】:
标签: javascript node.js json express try-catch