Search code examples
pythonazureserverlessazure-servicebus-queues

How to return queue message to Azure Service Bus Queue if Azure Service Bus Queue Trigger Func Fails


I created an Azure Service Bus Queue Trigger Python Function with Visual Studio Code and I would like to return the message to the Service Bus Queue if my code fails.

import requests
import azure.functions as func
from requests.exceptions import HTTPError

def main(msg: func.ServiceBusMessage):
    message = msg.get_body().decode("utf-8")

    url = "http://..."

    # My code
    try: 
         requests.post(url=url, params=message)
    except Exception as error:
         logging.error(error)
         # RETURN MESSAGE TO QUEUE HERE

I found some info about a method called unlock() and abandon() but I don't know how to implement it. Here are the links to such docs:

I also found that the queue would automatically send the message to the queue if the function fails, but then, should I write a raise... to send an Exception in the function?

Also, is there a way to return this message to the queue and set a schedule to retry later?


Solution

  • Service bus trigger python function runs in PeekLock mode. You don't have to call unlock() and abandon() method. Check the PeekLock behavior description:

    The Functions runtime receives a message in PeekLock mode. It calls Complete on the message if the function finishes successfully, or calls Abandon if the function fails. If the function runs longer than the PeekLock timeout, the lock is automatically renewed as long as the function is running.