【问题标题】:Two awaits with try/catch使用 try/catch 进行两次等待
【发布时间】: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


【解决方案1】:

似乎https://pokeapi.co/api/v2/pokemon API 没有快速响应或出现问题。如果您对此 API 没有更多控制权,则可以 设置 API 调用超时。如果在该时间段内 API 没有响应,请执行进一步操作。

或者试试下面的代码:

router.get('/pokemons', async (req, res) => {
    try {
        const { name } = req.query;

        let apiName = "";

        try {
          apiName = await axios.get(`https://pokeapi.co/api/v2/pokemon/${name}`);
        }
        catch (err) {
          console.log(err)
        }

        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
        })
    }
});

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    相关资源
    最近更新 更多