Ammar
Ammar

Reputation: 233

Is it better to handle MessagingEntityNotFoundException or should i check for Topic existance before sending message

In the code sample in documentation for Microsoft ServiceBus following code is used to make sure that the topic exists.

// Create the topic if it does not exist already
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

var namespaceManager = 
NamespaceManager.CreateFromConnectionString(connectionString);

if (!namespaceManager.TopicExists("TestTopic"))
{
    namespaceManager.CreateTopic("TestTopic");
}

But I want to know how expensive the TopicExists call will be, if I put this code before sending the message. (assume that I don't want to have initialization code separately)

Alternative approach is to be optimistic and send the message without checking for topic existence and handling MessagingEntityNotFoundException. In case of the exception we can create the topic and retry sending the message.

The second approach seems better to me, but I couldn't find any reference supporting it. So I want to know that, is there a particular reason that Microsoft in their documentation and samples chose the first approach rather than handling the exception.

Upvotes: 1

Views: 873

Answers (1)

Ben Morris
Ben Morris

Reputation: 623

One thing to bear in mind is that you need Manage permissions to the bus to create a topic. You may not want to grant this level of permission to all your clients as this can be a bit of a security risk, e.g. a client could create a subscription to read messages it's not supposed to see.

Calling TopicExists() before opening a client connection isn't very expensive and will give rise to more graceful code. If you wait for an exception to be tripped before creating anything then you may find you have a slew of failed messages on your hands.

I normally have a separate process for creating and updating the structure of the bus. How practical this is depends on how many topics and queues you are creating.

Upvotes: 0

Related Questions