【发布时间】:2020-10-06 09:35:02
【问题描述】:
我试图从一个函数向另一个函数抛出一个错误并发送一个 res.status(402)。我以最基本的方式将其放入 try-catch 块中,但仍然出现错误。
:未处理的承诺拒绝。此错误源于抛出 在没有 catch 块的异步函数内部
这是调用函数:
const validateAction = async (req, res) => {
const { action, url, mail, orderId } = req.body;
try {
requestAction(action, url, mail, orderId);
} catch (err) {
console.error(err);
res.status(402).send({
status: 402,
error: "BUG",
});
}
这是我想要抛出错误的函数:
const requestAction = async (action, url, mail, oderId) => {
const result = actions.find((actionFind) => actionFind.action === action);
await axios({
//change the action to "add"
method: "post",
url: "XXXXXXXXXXXXXXXXXXXX",
data: {
key: "XXXXXXXXXXXXXXXXXXXXXXXX",
action: "XXXXX",
service: XXXXXX,
quantity: XXXXXXXXXX,
},
}).then(
(response) => {
if (response.data.error) {
sendLog(
` ${response.data.error} --- URL:${url} ACTION:${action} QUANTITY:${result.quantity} ID:${result.id}`,
"error"
);
// here is the throw that's not working---------------------------------------------
throw response.data.error;
//----------------------------------------------------------------------------------
} else {
sendMail(mail);
sendLog(
` Succesfully sent it --- URL:${url} ACTION:${action} QUANTITY:${result.quantity} ID:${result.id} To ${mail}`,
"info"
);
}
},
(error) => {}
);
};
我相信答案并不复杂但我没找到
【问题讨论】:
-
await requestAction(action, url, mail, orderId);. -
你可能想要 ->
await requestAction( -
是的 基本而简单。我的坏..
标签: javascript node.js error-handling