NodeJS 如何处理嵌套的 try/catch 机制

编程入门 行业动态 更新时间:2024-10-04 07:24:43

NodeJS 如何处理<a href=https://www.elefans.com/category/jswz/34/1771299.html style=嵌套的 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 机制

本文发布于:2024-05-30 23:30:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   如何处理   机制   NodeJS   catch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!