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

问题描述 投票:0回答:2

我是 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;
    }

javascript node.js rabbitmq
2个回答
1
投票

要确保外部 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);
}

1
投票

你不应该将回调传递给

channel.assertQueue
,而不是一个
async
回调,相反你应该 promisify 它。使用
await
,您可以捕获外部
try
/
catch
中的错误。

你可能正在寻找

async function attemptToSendMessage() {
  for (let retryCount = 0; retryCount < 5; retryCount++) {
    try {
      const queue = await new Promise((resolve, reject) => {
        channel.assertQueue(
          name,
          { durable: true, arguments: { "x-queue-type": "quorum" } },
          (error, queue) => {
            if (error) reject(error);
            else resolve(queue);
          }
        );
      });
      if (queue) {
        await channel.sendToQueue(name, Buffer.from(message));
      }
      return; // Exit the loop if the message is sent successfully
    } catch (e) {
      console.error(e);
    }
  }
  throw new Error("Failed to send message after 5 attempts.");
}
© www.soinside.com 2019 - 2024. All rights reserved.