两个带try/catch的await场景下API调用失败跳过数据库调用如何解决
你当前代码的问题核心是:await 等待的 Promise 状态变为 rejected 时会直接抛出异常,触发外层的 catch 分支,所以 axios 请求失败(比如接口返回404、网络异常)时,后续的数据库查询逻辑自然不会执行。你需要单独隔离第一个 axios 请求的异常,不要让它打断正常流程,有两种常见实现方案:
方案1:给 axios 请求单独嵌套 try/catch
单独捕获 axios 请求的异常,请求失败时把结果设为空,继续执行后续逻辑:
router.get('/pokemons', async (req, res) => { try { const { name } = req.query; let apiName; // 单独处理axios请求的异常 try { apiName = await axios.get(`https://pokeapi.co/api/v2/pokemon/${name}`) } catch (axiosErr) { apiName = null; } 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 }) } });
方案2:用 .catch() 直接处理 axios 的异常返回
不用嵌套 try/catch,直接在请求后加 catch 处理异常,失败时返回空值,代码更简洁:
router.get('/pokemons', async (req, res) => { try { const { name } = req.query; // 请求异常时直接返回null,不会抛出到外层catch const apiName = await axios.get(`https://pokeapi.co/api/v2/pokemon/${name}`).catch(() => null); 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 }) } });
两种方案都可以保证 axios 请求失败后正常执行数据库查询逻辑,只有当数据库查询或者其他后续逻辑出现异常时,才会进入外层 catch 分支返回404。
内容的提问来源于stack exchange,提问作者Estani Pettigrew
相关产品推荐
相关产品推荐

