Search code examples
pythonazureazureservicebus

Python Azure Service Bus Exception Handling - Generic Error


I am creating a health check which simply sends and receives a message from a service bus queue.

The code is very simple, but I am having issues with the error handling, no matter what error I test, for example providing the wrong access key, or turning ON the Service Bus Firewall to block traffic, I receive the same error:

Service Bus has encountered an error. Error condition: amqp:client-error.

Is there anyway to get a more descriptive error using the Python module?

Python Code:

def send_message(service_bus_connection_string, queue):
    try:
        # Create Client
        client = ServiceBusClient.from_connection_string(conn_str=service_bus_connection_string)

        # Create Sender.
        sender = client.get_queue_sender(queue_name=queue)

        # Get Date
        date = datetime.now()

        # Create Message
        message_to_send = "Health Check : {}".format(date)
        message = ServiceBusMessage(message_to_send)

        # Send Message
        sender.send_messages(message)

        # Print
        print("Successfully Sent Message:", "[", message, "]")

        # Exit
        client.close()
    except Exception as Err:
        print("Failed to send service bus message, this could be due to an error in the connection string or firewall settings.")
        print(Err)
        exit(1)

Also is there a better way I can handle the exception rather than using

except Exception as Err:

This code is working fine but I am looking for a more descriptive error to save me from needing to print POTENTIAL issues.

Version: azure-servicebus==7.11.4


Solution

  • Unfortunately, You cannot change the default Error messages as they are set on Azure's backend for troubleshooting and managing the error and exceptions from the logs at the backend. You can find some Service Bus Known Exceptions in this MS Document1 and MS Document2.

    As you mentioned, You can use except block with Exception as other_err and write your custom error messages to receive more details in your code like below:-

    from azure.servicebus import ServiceBusClient, ServiceBusMessage
    from datetime import datetime
    import socket
    
    def send_message(service_bus_connection_string="Endpoint=sb://siliconsb98.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxxxxSbERa+sQ=", queue="q1"):
        try:
            print("Connecting to Azure Service Bus...")
            # Create Client
            client = ServiceBusClient.from_connection_string(conn_str=service_bus_connection_string)
    
            # Create Sender.
            sender = client.get_queue_sender(queue_name=queue)
    
            # Get Date
            date = datetime.now()
    
            # Create Message
            message_to_send = "Health Check : {}".format(date)
            message = ServiceBusMessage(message_to_send)
    
            # Send Message
            sender.send_messages(message)
    
            # Print
            print("Successfully Sent Message:", "[", message, "]")
    
            # Exit
            client.close()
        except (ConnectionError, ValueError) as connection_err:
            print("Error in the connection string or service bus settings.")
            print(connection_err)
            exit(1)
        except socket.timeout as timeout_err:
            print("Failed to initiate the connection due to a timeout.")
            print("This might be due to firewall settings or network issues.")
            print(timeout_err)
            exit(1)
        except OSError as os_err:
            print("Failed to initiate the connection due to an OS-level error.")
            print("This could be caused by network configurations or firewall settings.")
            print(os_err)
            exit(1)
        except Exception as other_err:
            if "amqp" in str(other_err):
                print("Failed to send service bus message. Check connection string or firewall settings.")
                print(other_err)
                exit(1)
            else:
                print("An unexpected error occurred.")
                print(other_err)
                exit(1)
    
    # Call the function
    send_message()
    

    In this code I have added if "amqp" in str(other_err): to get the detailed custom exception for error related to amqp. If amqp is present in the exception.

    Output:-

    Connecting to Azure Service Bus...
    Failed to send service bus message. Check connection string or firewall settings.
    Failed to initiate the connection due to exception: timed out Error condition: amqp:socket-error.   
    

    enter image description here

    I tried changing the connection string and it automatically returned me invalid connection string error as that is already present in the Service bus messaging exception in the backend.

    Connecting to Azure Service Bus...
    Error in the connection string or service bus settings.
    Connection string is either blank or malformed.
    

    enter image description here