尝试在 Node JS 中的 then 方法中捕获 axios 内部


  • 在我点击下面的 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 方法中正确添加了尝试和捕获吗?
    • 在下面提供我的代码片段
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 serverservicesutilsResponseUtil.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.

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

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

1)未能将承诺链起来

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

2) 重复调用res.send

express deprecated 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');
});

最新更新