【发布时间】:2021-11-09 22:56:00
【问题描述】:
我该如何解决?如果 API 调用没有解析,就不会进入数据库调用,最终会陷入 catch 中
router.get('/pokemons', async (req, res) => {
try {
const { name } = req.query;
const apiName = await axios.get(`https://pokeapi.co/api/v2/pokemon/${name}`)
if (apiName) {
return res.status(200).json({
data: apiName.data.abilities
});
}
const dbName = await Pokemon.findAll({
where: {
name
}
})
return res.status(200).json({
data: dbName
})
} catch (err) {
res.status(404).json({
message: "No existe Pokemon con ese nombre",
error: err
})
}
});
【问题讨论】:
-
你得到什么错误?
-
是的,
try/catch就是这样工作的。如果您想以不同于第二个的方式处理第一个await中的错误,您可以将每个await包装在它们自己的 try/catch 中。
标签: node.js express async-await try-catch