Search code examples
c#rabbitmqrabbitmq-exchange

RabbitMQ not throwing error on invalid routing key


I have the following code in C#, which does not throw error if the routing key is invalid.

var connFactory = GetConnectionFactory();

using (var conn = connFactory.CreateConnection())
{
    using (var channel = conn.CreateModel())
    {
        channel.TxSelect();

        var publicationAddress = new PublicationAddress(ExchangeType.Direct, Settings.ServiceBusExchange, Settings.ServiceBusRoutingKey);

        var headers = new Dictionary<String, Object>();
        headers.Add("TransactionID", transactionID);

        var basicProperties = new BasicProperties();
        basicProperties.ContentEncoding = Encoding.UTF8.ToString();
        basicProperties.ContentType = "text/xml";
        basicProperties.Headers = headers;
        basicProperties.DeliveryMode = 2;

        var payLoad = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish(publicationAddress, basicProperties, payLoad);
        channel.TxCommit();
    }
}

My question is, how can I make the code throw error if the routing key is invalid? Like when I Publish a message using RabbitMQ UI with invalid routing key, it gives a message "Message published, but not routed."

Thanks in advance.


Solution

  • it does not exist the concept of "invalid routing key", since you can bind dynamically queues to the exchanges.

    Btw what you are looking for is "unroutable messages", you have to use the mandatory flag and implement the ReturnListener in the same channel, if a message does not reach any queue will be redirect to the handler. In this in this way (the code is Java, but in c# is more or less the same):

     boolean isMandatory = true; // if true the message will be handled by HandlingReturnListener
            // if false the message will be dropped!
    
            channel.addReturnListener(new ReturnListener() {
                public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println(replyText + ":" + replyCode);
                    System.out.println("********  UnHandled Message ***************");
    
                }
    
            });
    
            String myExchange = "myUnroutableExchange_";
            channel.exchangeDeclare(myExchange, "topic", false, false, null);
            channel.basicPublish(myExchange, "NO_KEY", isMandatory, null, "".getBytes());