【问题标题】:try catch inside axios in then method in node js尝试在节点 js 中的 then 方法中在 axios 中捕获
【发布时间】:2019-10-25 08:55:24
【问题描述】:
  • 点击下面的 api 调用后,我遇到了错误。 (node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. (node:5548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
    • 所以我将 try catch 放在 then 方法中,但仍然无法在 catch 中捕获错误。
    • 我通过输入控制台console.log("try catch error--->", error)进行了调试,但仍然没有帮助
    • 能否告诉我是否在 then 方法中正确添加了 try 和 catch。
    • 在下面提供我的代码 sn-p
   axios.get(AppConstants.GET_JWT_TOKEN_URL, {
        auth: {
            username: credentials.auth.racfId, password: credentials.auth.password
        }
    })
        .then((jwtResponse) => {
            console.log("jwt then----->", jwtResponse.data.jwt);
            var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
            //   var jwtToken = `Bearer ewefewehjefwwe wehwefwefwef uih uihu`;
            console.log('then formatUrl --->', formatUrl);

            axios.get(formatUrl, {
                headers: {
                    "Authorization": jwtToken, "Content-Type": 'application/json'

                }
            })

                .then((response) => {
                    try {
                        console.log("sports suceess then0--->");
                        const file = Buffer.from(response.data.content, 'base64');
                        const fileType = mime.contentType(response.data.contentInfo.fileType);
                        const fileExtension = response.data.contentInfo.fileType.toLowerCase();
                        const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
                        console.log("sports suceess fileName--->", fileName);
                        ResponseUtil.callService(res, url);

                        res.send({});
                    }
                    catch (error) {
                        console.log("try catch error--->", error)
                        const errorMessage = error.response.data.message;


                    }

                })


                .catch((e) => {
                    console.log("e catch sports0--->", e);
                    console.log("e.message catch sports0--->", e.message);

                    console.log("catch sports--->", e.response);

                    if (e.response) {
                        return res.status(e.response.status).send(e.response.data);
                    }
                    res.status(500).send(e.message || 'Something wrong');
                });



        });

日志

sports suceess then0--->

sports suceess fileName---> ioreioreio=erierioerioerio
  callService ===>  /erpoperoperop/rejklerklkler
  else if responseutil.jsURL ===>  http://players/erpoperoperop/rejklerklkler
  URL ===>  http://players/erpoperoperop/rejklerklkler
express deprecated res.send(status, body): Use res.status(status).send(body) instead server\services\utils\ResponseUtil.js:56:30
(node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:5548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

  • 你能重新表述一下这个问题吗?很难理解你在问什么。
  • @shaochuancs 嘿,抱歉在我发布之前确实看到了这个问题......我正在尝试实现 try catch iside axios then 方法:(

标签: javascript node.js api express


【解决方案1】:

这个实现有几个问题。第一个问题是您忽略了返回您的承诺,以便将它们应用于承诺链。如果你不返回 Promise,那么错误不会沿着 Promise 链传播,这违背了 Promise 的目的。第二个问题是您尝试发送两次响应,一次是在 ResponseUtil.callService(res, url) 中,另一次是在此之后(例如 res.send({});)。

控制台错误指出了这两个错误:

1) 未能链接承诺

(节点:5548)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):错误:发送后无法设置标头。

2) 重复调用res.send

表示不推荐使用 res.send(status, body):使用 res.status(status).send(body) 代替 server\services\utils\ResponseUtil.js:56:30


我将假设ResponseUtil.callService(res, url) 会返回一个回答这个问题的承诺,因为看起来确实如此。

axios.get(AppConstants.GET_JWT_TOKEN_URL, {
    auth: {
        username: credentials.auth.racfId,
        password: credentials.auth.password
    }
}).then((jwtResponse) => {
    // Return the promise from get so it is applied to the promise chain
    return axios.get(formatUrl, {
        headers: {
            "Authorization": `Bearer ${jwtResponse.data.jwt}`,
            "Content-Type": 'application/json'

        }
    }).then((response) => {
        const file = Buffer.from(response.data.content, 'base64');
        const fileType = mime.contentType(response.data.contentInfo.fileType);
        const fileExtension = response.data.contentInfo.fileType.toLowerCase();
        const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
        // Return the promise from call service so it is applied to the promise chain
        return ResponseUtil.callService(res, url);
    });
}).catch((e) => {
    // Catch any error that occurred in the promise chain...
    if (e.response) {
        return res.status(e.response.status).send(e.response.data);
    }
    return res.status(500).send(e.message || 'Something wrong');
});

【讨论】:

  • 感谢错误消失了...我更新了我的问题。你能告诉我如何删除负面标记:(
  • 如果去掉这行res.send({});怎么把数据发送到浏览器?因为在浏览器中我需要下载 pdf
  • ResponseUtil 正在发送响应。错误消息说不要使用res.send(status, body),它来自ResponseUtil。不幸的是,您无法删除其他用户给出的负面标记,他们可能会给您负面标记,因为您的帖子最初格式错误。为避免将来出现这种情况,请确保您的问题在发布之前格式正确。您当然可以删除您的问题,这会从您的帐户中删除负面标记。
  • 但给出了很好的解释,这将对其他人有所帮助......无论如何我可以删除负面标记而不删除:(
  • 您可以尝试进一步改进问题的格式,使其更具可读性。如果您改进其他用户可能会提出并给予支持的问题,每个人可能都不清楚您在问什么。通常,提出问题的一个好方法是包含有关您要解决的问题的信息。您的问题假定使用try/catch 是您的问题的解决方案,我们喜欢称之为XY problem
猜你喜欢
  • 2020-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2015-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多