Messages that are not successfully processed are termed as dead letter messages in the azure service bus. The dead letter queue holds all the dead letter messages that for some reason are not processed successfully. DLQ is subqueue of the main queue. There can be many reasons for the dead letter messages such as :
Header Size can Exceed its maximum.
Time to live expired exception.
The session ID can be null.
Maximum Delivery Count can exceed.
In case we want to access dead letters for getting certain details or even for completing the message in the subqueue, we can do that via C# code:
Nuget package : Azure.Messaging.ServiceBus
Following is the code snippet for getting the list of dead letters in the dead letter Queue:
await using var client = new ServiceBusClient(“Connectionstrings”);
ServiceBusReceiver Deadletters= client.CreateReceiver(
“QueueName”,
new ServiceBusReceiverOptions { SubQueue=SubQueue.DeadLetter });
IReadOnlyList messageList= await Deadletters.PeekMessagesAsync(100);
Here QueueName will be name of the Queue for which the dead letters need to be fetched.
The Connectionstrings will be the Primary Connections strings for the Service bus Queue( This is specific for a particular queue)
You can get the connection strings by the following the below path:
Service Bus>Queues>Queuename>Settings>SharedPolicies>Policy>Primary Connection Strings
The maximum number of messages that can be fetched is 250. To retrieve all the messages, we can fetch with the sequence number in batches with following syntax:
IReadOnlyList messageList= await Deadletters.PeekMessagesAsync(No of messages, Sequence number);
IReadOnlyList messageList= await Deadletters.PeekMessagesAsync(100,1);
IReadOnlyList messageList= await Deadletters.PeekMessagesAsync(100,101);
This way messages can be fetched in batches.