【问题标题】:Node/Express return error to main function?Node/Express 向主函数返回错误?
【发布时间】:2021-12-24 09:45:20
【问题描述】:

我的情况是,我有一个多次调用函数的 POST 路由。如果调用的函数返回错误,我希望请求返回错误,但我不确定如何实现。看这张图片:

这是我的代码:

function POSTcord(lat, lng) {
    axios
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    .catch(error => {
        console.error(error.message);
    })
}

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        for (const cord of passedCords) {
            POSTcord(cord.lat, cord.lng);
        }
        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});

如果函数POSTcord 在循环中的某处捕获错误,我希望路由/test 返回错误。对此有什么想法吗?我想我可以将res 传递给POSTcord 函数,但这不起作用。感谢您的任何意见:)

【问题讨论】:

  • 多个问题:你的 POSTcord 函数没有 return 任何东西,你不是 awaiting POSTcord() 调用,即使你做了两个然后 .catch(error => { console.error(error.message); }) 会吞下任何错误并简单地返回undefined

标签: javascript node.js express for-of-loop


【解决方案1】:

您需要返回 Promise 并确保错误被​​抛出/拒绝:

要么这样做:

function POSTcord(lat, lng) {
    return axios // <--------------- THIS IS VERY IMPORTANT
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    .catch(error => {
        console.error(error.message);
        throw error; // <----------- ALSO DO THIS
    })
}

或者这样做:

function POSTcord(lat, lng) {
    return axios // <--------------- THIS IS VERY IMPORTANT
    .post(process.env.SOS_POST_URL + process.env.SOS_POST_CODE, {
        batteryLevel: 100,
        longitude: lng,
        latitude: lat
    })
    .then(res => {
        console.log(`statusCode: ${res.status}`)
    })
    // DON'T CATCH THE ERROR!!
}

那么你需要做的就是await得到错误:

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        for (const cord of passedCords) {
            await POSTcord(cord.lat, cord.lng); // DO THIS FOR CATCH TO WORK
        }
        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});

如果您想并行调用POSTcord(),您可以使用Promise.all()await

router.post('/test', async (req, res) => {
    let passedCords = req.body;
    try {
        let promises = [];
        for (const cord of passedCords) {
            let p = POSTcord(cord.lat, cord.lng);
            promises.push(p);
        }

        await Promise.all(promises); // DO THIS FOR CATCH TO WORK

        res.status(200).json({status:"success", message: "hello!"});
      } catch (err) {
        console.error(err.message);
        res.status(500).send("Server error");
      }
});

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2019-11-07
    • 2015-05-25
    • 2016-06-25
    • 2018-06-30
    • 2020-12-16
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多