I’m new to Node.js and I’m trying to code two nested try/catch and put retry logic for it. So when inner try/catch catches error I want it to send to outer catch and inside of it I will increase retry count by 1. So when it comes to 5 I will return from while loop. But my problem is that when inner try/catch throws an exception it is not caught by outer one. How can I make sure that it catches the error?
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;
}
2
Answers
To ensure that the outer catch block catches the error thrown in the inner try/catch block, you can modify your code as follows:
You shouldn’t pass a callback to
channel.assertQueue
, and not anasync
one for certain, instead you should promisify it. Withawait
, you can then catch the errors in the outertry
/catch
.You’re probably looking for
However, assuming you are using this API, you don’t even need to promisify the
assertQueue
function yourself – it already returns a promise if you don’t pass a callback. So simplify further to