Search code examples
c#azureazure-functionsservicebus

Azure function app, service bus and return service bus


I have an azure function with a service bus input attribute and service bus output attribute set.

This means that whatever I return from this function will be returned to the ‘return’ queue.

However, i want to manually handle some messages as there is no point retrying them I just want to put them straight on the LDQ and carry on.

So i added MessageReceiver as a parameter with lockToken.

All good.

But now, if i handle the message and send to DLQ i have no way ending the function execution gracefully as it is expecting a return. So i throw an exception. But now i have numerous error logs in the output like ‘lock is invalid’.

I tried to set autocomplete to false but then i have a different issue; how do i ensure i can return the message AND log it in a transaction and handle rollback?

Any guidance??

Example:

  public static class Function1
    {
        [FunctionName("Function1")]
        [return: ServiceBus("returnQueueName", Connection = "myConnectionString")]
        public static async System.Threading.Tasks.Task<ReturnMessage> RunAsync([ServiceBusTrigger("mytopic", "mysubscription", Connection = "myConnectionString")]
        string mySbMsg, ILogger log,
            MessageReceiver messageReceiver, string lockToken)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");

            await messageReceiver.DeadLetterAsync(lockToken);

            return new ReturnMessage();
        }
    }

    public class ReturnMessage
    {
        public string Payload { get; set; }
    }

Hopefully you can see that the input queue and output queue are handled by the hosting system - Azure. I like this because it will look after atomcity for me.

But if I include the line:

await messageReceiver.DeadLetterAsync(lockToken);

This will move the current message to the DLQ.

GREAT!!! That's what I want.

But I am now forced to return something OR throw an exception. Is there any way out of this as seeing the error messages is misleading as there is no error to follow.


Solution

  • As far as I can see it appears that you shouldn't use an automatic return service bus binding. Instead, you should manually connect to the return topic/queue and handle the message logistics manually.