sendToQueue() of amqplib doesn't throw any error even if the queue does't exist

655 Views Asked by At

I created a queue named 'test_queue' with amqplib

then I deleted the 'test_queue' from the admin page of rabbitmq (http://localhost:15672/#/queues)

but when I excute the following code, it shows 'sent message successfully!'

there is no error even if the queue named 'test_queue' does't exist

How to get an error when queue doesn't exist?

Thanks for any help!

const amqp = require('amqplib');

const sendMsg=async ()=>{

    const connection = await amqp.connect('amqp://localhost');
    const ch = await connection.createConfirmChannel()  

    const msg= 'hello world'
    const QUEUE_NAME = 'test_queue'

    ch.sendToQueue(QUEUE_NAME, Buffer.from(msg),{},function(err, ok) {
        if (err !== null) {
            console.log(err);
        } else {
            console.log('sent message successfully!');
        }
    })

    // await ch.close();
    // await connection.close();
}

sendMsg();
1

There are 1 best solutions below

0
On

If you add the mandatory flag to sendToQueue any message which cannot be routed to a queue will be sent back to the publisher. So from your example you would need:

ch.sendToQueue(QUEUE_NAME, Buffer.from(msg),{mandatory: true},function(err, ok)

You can then handle the return using the same channel object:

ch.on('return', (message) => {
    console.log(`Unable to route message to ${QUEUE_NAME}`)
}