Azure/azure-iot-sdk-python

ERROR Handling

luck0r opened this issue · 2 comments

HI, i have a problem handling errors with IoT Hub python SDK.
Im using azure-iot-device 2.12.0 and imported import azure.iot.device.exceptions as iot_exceptions

The goal is to have stable connection while sending a lot of messages from iot edge to azure.

This is used to start the client:
self.client = IoTHubModuleClient.create_from_connection_string(self.Device_Connection_String) self.client.on_background_exception = self.handle_background_exception
i also have this try except block at every point where i use the client:

try:
    self.client.send_message_to_output(str(cache), "output1")
    self.logger.info("Message sent to IoT Hub successfully")

                                                

except Exception as e:
    self.handle_background_exception(e)
    self.logger.error(f"Sending to IoT Hub Error: {e}")
    self.logger.exception(e)

This is the handler:

def handle_background_exception(self, e):
        if isinstance(e, iot_exceptions.ConnectionFailedError):
            # Handle connection errors
            self.logger.error(f"Connection error occurred: {e}")

        elif isinstance(e, iot_exceptions.CredentialError):
            # Handle authentication errors
            self.logger.error(f"Authentication error occurred: {e}")

        elif isinstance(e, iot_exceptions.ProtocolClientError):
            self.logger.error(f"Protocol error occurred: {e}")

        if isinstance(e, iot_exceptions.HandlerManagerException):
            # Special handling for HandlerManagerException
            self.logger.error(f"HandlerManagerException occurred: {e}")
            self.logger.info(f"Additional Information: {e.__cause__}")

        self.logger.info(f"Error handling completed: {e}")
        time.sleep(1)

I get no of the logger messages above.
It appears that the expections are not intercepted and still printing differently:

 WARNING - Exception caught in background thread.  Unable to handle.
2024-01-28 14:20:21,119 - WARNING - ['azure.iot.device.common.transport_exceptions.ConnectionDroppedError: Unexpected disconnection\n']
2024-01-28 14:20:21,120 - WARNING - Exception caught in background thread.  Unable to handle.
2024-01-28 14:20:21,120 - WARNING - ['azure.iot.device.iothub.sync_handler_manager.HandlerManagerException: HANDLER (CLIENT_EVENT): Error during invocation\n']


Your handler is catching exceptions raised from the client method (client.send_message_to_output()), which are not "background exceptions". What we call "background exceptions" (and the ones that are showing up in your logs that you have not intercepted) refer to exceptions that occur in background threads that cannot be raised due to not being a result of an action initiated by your application (for instance, a background thread experiences an error invoking a callback) - there's nowhere to raise them to.

If you would like to intercept these "background exceptions" there is a handler/callback you can set on the client called on_background_exception. Simply set that property (client.on_background_exception) to a function that takes a single argument (an exception object).

Thanks for the explanation.