嵌套的 try/catch 机制"/>
NodeJS 如何处理嵌套的 try/catch 机制
我是 Node.js 的新手,我正在尝试编写两个嵌套的 try/catch 代码并为其放置重试逻辑。因此,当内部 try/catch 捕获错误时,我希望它发送到外部 catch 并在其中将重试计数增加 1。因此,当达到 5 时,我将从 while 循环返回。但我的问题是,当内部 try/catch 抛出异常时,它不会被外部捕获。我怎样才能确保它捕捉到错误?
try {
channel.assertQueue(name, { durable: true, arguments: { "x-queue-type": "quorum" } }, async (error, queue) => {
if (error)
throw error;
if (queue) {
try {
channel.sendToQueue(name, Buffer.from(message));
} catch (e) {
console.log(e);
throw e;
}
}
});
} catch (e) {
//retry count will be increased.
throw e.message;
}
回答如下:
要确保外部 catch 块捕获内部 try/catch 块中抛出的错误,您可以按如下方式修改代码:
let retryCount = 0;
async function attemptToSendMessage() {
while (retryCount < 5) {
try {
await new Promise((resolve, reject) => {
channel.assertQueue(
name,
{ durable: true, arguments: { "x-queue-type": "quorum" } },
async (error, queue) => {
if (error) {
reject(error); // Reject the promise if an error occurs
return;
}
if (queue) {
try {
channel.sendToQueue(name, Buffer.from(message));
resolve(); // Resolve the promise if the message is sent successfully
} catch (e) {
reject(e); // Reject the promise if an error occurs while sending the message
}
}
}
);
});
break; // Exit the while loop if the message is sent successfully
} catch (e) {
console.log(e);
retryCount++; // Increase the retry count
}
}
if (retryCount === 5) {
throw new Error("Failed to send message after 5 attempts.");
}
}
// Usage
try {
await attemptToSendMessage();
} catch (e) {
// Handle the error here
console.log(e.message);
}
更多推荐
NodeJS 如何处理嵌套的 try/catch 机制
发布评论